package com.quanyan.place.biz.impl;

import static com.quanyan.place.constants.PlaceConstants.UNIT_TYPE_COMBINE;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.validation.constraints.NotNull;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.Predicate;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import baidu.webapi.LBSApi;
import baidu.webapi.impl.BaiduLBS;
import baidu.webapi.model.AddressComponent;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.comment.reqeust.ReqIsComment;
import com.quanyan.comment.serviceFacade.CommentServiceFacade;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.enums.SysParameterConfigEnum;
import com.quanyan.common.utils.BeanCopierUtils;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.common.utils.DateTimeUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.PinYinUtils;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.common.utils.UUIDUtils;
import com.quanyan.common.vo.Image;
import com.quanyan.place.biz.IBaseService;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.Cagetory;
import com.quanyan.place.entity.CagetoryExample;
import com.quanyan.place.entity.Dict;
import com.quanyan.place.entity.DictExample;
import com.quanyan.place.entity.TbAdminUser;
import com.quanyan.place.entity.TbBizPlace;
import com.quanyan.place.entity.TbBizPlaceAttach;
import com.quanyan.place.entity.TbBizPlaceCategory;
import com.quanyan.place.entity.TbBizPlaceCategoryExample;
import com.quanyan.place.entity.TbBizPlaceExample;
import com.quanyan.place.entity.TbBizPlaceMemberCard;
import com.quanyan.place.entity.TbBizPlaceMemberCardExample;
import com.quanyan.place.entity.TbBizPlaceOrder;
import com.quanyan.place.entity.TbBizPlaceOrderDiscountItem;
import com.quanyan.place.entity.TbBizPlaceOrderExample;
import com.quanyan.place.entity.TbBizPlaceOrderItem;
import com.quanyan.place.entity.TbBizPlaceOrderItemExample;
import com.quanyan.place.entity.TbBizPlacePayItem;
import com.quanyan.place.entity.TbBizPlacePayItemExample;
import com.quanyan.place.entity.TbBizPlaceRule;
import com.quanyan.place.entity.TbBizPlaceRuleExample;
import com.quanyan.place.entity.TbBizPlaceUnitSalePlan;
import com.quanyan.place.entity.TbBizPlaceUnitSalePlanExample;
import com.quanyan.place.entity.TbBizPlaceUnitTime;
import com.quanyan.place.entity.TbBizPlaceUnitTimeExample;
import com.quanyan.place.entity.TbCity;
import com.quanyan.place.entity.TbCityExample;
import com.quanyan.place.entity.TbCommonParameter;
import com.quanyan.place.entity.TbDistrict;
import com.quanyan.place.entity.TbDistrictExample;
import com.quanyan.place.entity.TbPlaceImage;
import com.quanyan.place.entity.TbPlaceImageExample;
import com.quanyan.place.entity.apireq.ReqBillingInfo;
import com.quanyan.place.entity.apireq.ReqPlaceOrderListVo;
import com.quanyan.place.entity.apireq.ReqPlaceSalePlan;
import com.quanyan.place.entity.apiresp.RespBizPlaceBaseInfo;
import com.quanyan.place.entity.apiresp.RespBizPlaceSalePlanOrderInfo;
import com.quanyan.place.entity.apiresp.RespCategory;
import com.quanyan.place.entity.apiresp.RespCity;
import com.quanyan.place.entity.apiresp.RespCityInfo;
import com.quanyan.place.entity.apiresp.RespImage;
import com.quanyan.place.entity.apiresp.RespPlaceUnitInfo;
import com.quanyan.place.entity.apiresp.RespPlaceUnitInfoVo;
import com.quanyan.place.entity.apiresp.RespPlaceUnitSalePlan;
import com.quanyan.place.entity.apiresp.RespPlaceUnitSalePlanByDay;
import com.quanyan.place.entity.apiresp.RespPlaceUnitSalePlanDetail;
import com.quanyan.place.entity.apiresp.RespPlaceUnitSalePlanVo;
import com.quanyan.place.entity.apiresp.RespPlaceUserInfo;
import com.quanyan.place.entity.apiresp.RespUserBizPlaceOrderInfo;
import com.quanyan.place.entity.base.apiresp.RespDistrict;
import com.quanyan.place.entity.vo.PlaceCommonDataVo;
import com.quanyan.place.entity.vo.PlaceUnitSalePlan;
import com.quanyan.place.entity.vo.UnitSalePlan;
import com.quanyan.place.enums.PayTypeEnum;
import com.quanyan.place.mapper.CagetoryMapper;
import com.quanyan.place.mapper.DictMapper;
import com.quanyan.place.mapper.PlaceUnitSalePlanMapper;
import com.quanyan.place.mapper.TbAdminUserMapper;
import com.quanyan.place.mapper.TbBizPlaceAttachMapper;
import com.quanyan.place.mapper.TbBizPlaceCategoryMapper;
import com.quanyan.place.mapper.TbBizPlaceMapper;
import com.quanyan.place.mapper.TbBizPlaceMemberCardMapper;
import com.quanyan.place.mapper.TbBizPlaceMemberOpHistoryMapper;
import com.quanyan.place.mapper.TbBizPlaceOrderItemMapper;
import com.quanyan.place.mapper.TbBizPlaceOrderManagerMapper;
import com.quanyan.place.mapper.TbBizPlaceOrderMapper;
import com.quanyan.place.mapper.TbBizPlacePayItemMapper;
import com.quanyan.place.mapper.TbBizPlacePrivateOrderMapper;
import com.quanyan.place.mapper.TbBizPlaceRuleMapper;
import com.quanyan.place.mapper.TbBizPlaceUnitSalePlanMapper;
import com.quanyan.place.mapper.TbBizPlaceUnitTimeMapper;
import com.quanyan.place.mapper.TbCityMapper;
import com.quanyan.place.mapper.TbDistrictMapper;
import com.quanyan.place.mapper.TbPlaceImageMapper;
import com.quanyan.place.service.BaseService;
import com.quanyan.place.service.PlaceBaseService;
import com.quanyan.place.service.PlaceMemberService;
import com.quanyan.place.service.PlaceOrderUtilService;
import com.quanyan.place.service.PlaceTicketService;
import com.quanyan.place.service.PlaceUnitCombineService;
import com.quanyan.redisCluster.config.RedisTemplate;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.redisCluster.utils.RedisKey;
import com.quanyan.search.entity.vo.PlaceIndexInfo;
import com.quanyan.sms.service.SmsService;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserServiceFacade;

/**
 * Created by jingliu on 16/6/1.
 */
@Service
public class BaseServiceImpl implements IBaseService {
    private static final Logger logger = LoggerFactory.getLogger(BaseServiceImpl.class);
    @Autowired
    TbCityMapper tbCityMapper;
    @Autowired
    TbDistrictMapper tbDistrictMapper;
    @Autowired
    CagetoryMapper cagetoryMapper;
    @Autowired
    DictMapper dictMapper;
    @Autowired
    TbBizPlaceUnitSalePlanMapper tbBizPlaceUnitSalePlanMapper;
    @Autowired
    TbBizPlaceUnitTimeMapper tbBizPlaceUnitTimeMapper;
    @Autowired
    TbBizPlaceOrderMapper tbBizPlaceOrderMapper;
    @Autowired
    TbBizPlaceOrderItemMapper tbBizPlaceOrderItemMapper;
    @Autowired
    TbBizPlaceMapper tbBizPlaceMapper;
    @Autowired
    TbPlaceImageMapper tbPlaceImageMapper;
    @Autowired
    TbBizPlaceCategoryMapper tbBizPlaceCategoryMapper;
    @Autowired
    TbBizPlacePayItemMapper tbBizPlacePayItemMapper;
    @Autowired
    PlaceUnitSalePlanMapper placeUnitSalePlanMapper;
    @Autowired
    TbBizPlaceRuleMapper tbBizPlaceRuleMapper;
    @Autowired
    private CommentServiceFacade commentServiceFacade;
    @Autowired
    private TbBizPlaceOrderManagerMapper tbBizPlaceOrderManagerMapper;
    @Autowired
    private PlaceMemberService placeMemberService;
    @Autowired
    private TbBizPlaceMemberCardMapper tbBizPlaceMemberCardMapper;
    @Autowired
    private TbBizPlaceMemberOpHistoryMapper tbBizPlaceMemberOpHistoryMapper;
    @Autowired
    TbBizPlaceAttachMapper tbBizPlaceAttachMapper;
    @Autowired
    TbAdminUserMapper tbAdminUserMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    PlaceBaseService placeBaseService;

    @Autowired
    UserServiceFacade userServiceFacade;


    @Autowired
    SmsService smsService;

    @Autowired
    BaseService baseService;

    @Autowired
    TbBizPlacePrivateOrderMapper tbBizPlacePrivateOrderMapper;

    @Autowired
    PlaceTicketService placeTicketService;

    @Autowired
    PlaceUnitCombineService pucService;

    @Autowired
    PlaceOrderUtilService placeOrderUtilService;



    static Map<String,String> placeCommonDataMap = new HashMap<String,String>();

    @Override
    public String getCityTest() {
        StringBuilder sb = new StringBuilder();
        TbBizPlaceExample tbBizPlaceExample = new TbBizPlaceExample();
        tbBizPlaceExample.createCriteria();
        List<TbBizPlace> tbBizPlaces = tbBizPlaceMapper.selectByExample(tbBizPlaceExample);
        List ids = Lists.newArrayList(1,2,3,4,5,6);

        for(TbBizPlace tbBizPlace : tbBizPlaces){
            Double lng = tbBizPlace.getLng();
            Double lat = tbBizPlace.getLat();
            APIResponse<?> resp = this.getCitys(null,true,true,lng,lat);
            if (resp.isRet()){
                Map map = (Map) resp.getData();
                com.quanyan.common.vo.resp.RespCity tbCity = (com.quanyan.common.vo.resp.RespCity) map.get("city");
                if (null == tbCity || !ids.contains(tbCity.getId())){
                    sb.append(tbBizPlace.getId() + ",");
                }
            }
        }
        return sb.toString();
    }

    @Override
    public List<RespCityInfo> getSysCityInfo(Integer clientType) {
        //查询城市列表
        TbCityExample tbCityExample = new TbCityExample();
        TbCityExample.Criteria criteria = tbCityExample.createCriteria();
        criteria.andIsActiveEqualTo(Constants.IS_ACTIVE);
        criteria.andIsEnableEqualTo(Constants.IS_YES);
        List<TbCity> cities = tbCityMapper.selectByExample(tbCityExample);
        if (CollectionUtils.isEmpty(cities)) {
            return null;
        }
        //查询地区列表
        TbDistrictExample tbDistrictExample = new TbDistrictExample();
        List<TbDistrict> tbDistricts = tbDistrictMapper.selectByExample(tbDistrictExample);
        if (CollectionUtils.isEmpty(tbDistricts)) {
            return null;
        }
        List<RespCityInfo> respCityInfos = new ArrayList<RespCityInfo>();
        for (TbCity tbCity : cities) {
            RespCityInfo respCityInfo = new RespCityInfo();
            RespCity respCity = new RespCity();
            BeanUtils.copyProperties(tbCity, respCity);
            //获取城市对应区列表
            List<RespDistrict> respDistrictList = new ArrayList<RespDistrict>();
            if (clientType != null && clientType == 1) {
                RespDistrict allDistrict = new RespDistrict();//添加全城子项
                allDistrict.setCityId(tbCity.getId());
                allDistrict.setId(0);//默认区域Id为0
                allDistrict.setName("全" + tbCity.getName());
                respDistrictList.add(0, allDistrict);//全城置顶
            }
            for (TbDistrict tbDistrict : tbDistricts) {
                if (tbCity.getId() == tbDistrict.getCityId().intValue()) {
                    RespDistrict respDistrict = new RespDistrict();
                    BeanUtils.copyProperties(tbDistrict, respDistrict);
                    respDistrictList.add(respDistrict);
                } else {
                    continue;
                }
            }
            respCityInfo.setRespDistrict(respDistrictList);
            respCityInfo.setRespCity(respCity);
            respCityInfos.add(respCityInfo);
        }
        return respCityInfos;
    }

    @Override
    public List<RespCategory> getSysCategroyInfo() {
        CagetoryExample cagetoryExample = new CagetoryExample();
        cagetoryExample.createCriteria().andIsDeleteEqualTo(Constants.IS_DELETE_FALSE)
                .andIsEnableEqualTo(Constants.IS_ENABLE_TRUE);
        List<Cagetory> cagetories = cagetoryMapper.selectByExample(cagetoryExample);
        if (CollectionUtils.isNotEmpty(cagetories)) {
            List<RespCategory> respCategories = new ArrayList<RespCategory>();
            for (Cagetory cagetory : cagetories) {
                RespCategory respCategory = new RespCategory();
                BeanUtils.copyProperties(cagetory, respCategory);
                respCategories.add(respCategory);
            }
            //将categories存入缓存
            RedisKey rediskey = new RedisKey(RedisConstants.PLACE_FAMILY_KEY,
                    PlaceConstants.PLACE_ALL_CATEGORIES_REDIS_KEY);
            redisTemplate.set(rediskey,respCategories);
            return respCategories;
        }
        return null;
    }

    @Override
    public AddressComponent getAddressInfo(Double lat, Double lng) {
        if (StringUtils.isEmpty(lng)) {
            lng = Constants.BEIJING_LNG;
        }
        if (StringUtils.isEmpty(lat)) {
            lat = Constants.BEIJING_LAT;
        }
        LBSApi lbsApi = new BaiduLBS();
        AddressComponent addressComponent = lbsApi.getAddressComponentByLatAndLng(lat, lng);
        if (addressComponent == null) {
            return null;
        }
        String cityName = addressComponent.getCity();
        if (cityName == null || "".equals(cityName)) {
            return null;
        }
        return addressComponent;
    }

    /**
     * 获取城市列表
     * @param provinceId 省份id
     * @param isPublic  是否公开
     * @param isActive  是否开通
     * @return
     */
    @Override
    public APIResponse<?> getCitys(Integer provinceId,
                                   boolean isActive,
                                   boolean isPublic,
                                   Double lng,
                                   Double lat) {
        TbCityExample example = new TbCityExample();
        TbCityExample.Criteria criterial = example.createCriteria();
        if (provinceId != null) {
            criterial.andProvinceIdEqualTo(provinceId);
        }
        if (isActive){
            criterial.andIsActiveEqualTo(Constants.IS_ACTIVE);
        }
        if (isPublic){
            criterial.andIsPublicEqualTo(Constants.YES);
        }
        criterial.andIsEnableEqualTo(Constants.IS_YES);
        List<TbCity> cityList = tbCityMapper.selectByExample(example);
        Map resp = new HashMap();
        TbCity tbCity = null;

        APIResponse<TbCity> response = this.getCity(lng, lat);
        if (response.isRet()){
            tbCity = response.getData();
        }else{
            tbCity = tbCityMapper.selectByPrimaryKey(1);
        }
        List<com.quanyan.common.vo.resp.RespCity> respCityList = new ArrayList<>();
        if (cityList != null && cityList.size()>0) {
            for (TbCity city : cityList) {
                com.quanyan.common.vo.resp.RespCity respCity = new com.quanyan.common.vo.resp.RespCity();
                respCity.setId(city.getId());
                respCity.setLat(city.getLat());
                respCity.setLng(city.getLng());
                respCity.setName(city.getName());
                respCity.setIsActive(city.getIsActive());
                Image image = new Image();
                image.setImageUrl(city.getAttachUrl());
                respCity.setImage(image);
                respCityList.add(respCity);
            }
        }
        com.quanyan.common.vo.resp.RespCity city = new com.quanyan.common.vo.resp.RespCity();
        city.setId(tbCity.getId());
        city.setLat(tbCity.getLat());
        city.setLng(tbCity.getLng());
        city.setName(tbCity.getName());
        city.setIsActive(tbCity.getIsActive());
        Image image = new Image();
        image.setImageUrl(tbCity.getAttachUrl());
        city.setImage(image);
        resp.put("city",city);
        resp.put("citys",respCityList);
        return APIResponse.returnSuccess(resp);
    }


    @Override
    public APIResponse<TbCity> getCity(Double lng, Double lat) {
        if (StringUtils.isEmpty(lng)) {
            lng = Constants.BEIJING_LNG;
        }
        if (StringUtils.isEmpty(lat)) {
            lat = Constants.BEIJING_LAT;
        }
        AddressComponent addressComponent = this.getAddressInfo(lat, lng);
        if (StringUtils.isEmpty(addressComponent)) {
            logger.warn("未知地区:AddressComponent--{}",JSON.toJSONString(addressComponent));
            return APIResponse.returnFail("未知地区");
        }

        TbCity tbCity = this.getTbCityByAddressComponent(addressComponent);
        if (StringUtils.isEmpty(tbCity)) {
            logger.warn("无法获取城市名称:AddressComponent--{}",JSON.toJSONString(addressComponent));
            return APIResponse.returnFail("无法获取城市名称");

        }
        return APIResponse.returnSuccess(tbCity);
    }

    @Override
    public TbCity getTbCityByAddressComponent(AddressComponent addressComponent) {
        if (StringUtils.isEmpty(addressComponent)) {
            return null;
        }
        //截取“市”之前的信息，这样的话就可以处理遇到的问题
        String cityName = addressComponent.getCity();
        if (cityName.lastIndexOf("市") != -1) {
            cityName = cityName.substring(0, cityName.lastIndexOf("市"));
            TbCityExample example = new TbCityExample();
            TbCityExample.Criteria criteria = example.createCriteria();
            criteria.andNameLike(cityName);  //模糊匹配城市
            int count = tbCityMapper.countByExample(example);
            if (count == 1) {
                Integer cityId = tbCityMapper.selectByExample(example).get(0).getId();
                if (cityId != null) {
                    TbCity tbCity = tbCityMapper.selectByPrimaryKey(cityId);
                    return tbCity;
                }
            }
        }
        return null;
    }

    @Override
    public TbDistrict getTbDistrictByAddressComponent(AddressComponent addressComponent) {
        if (StringUtils.isEmpty(addressComponent)) {
            return null;
        }
        //截取“市”之前的信息，这样的话就可以处理遇到的问题
        String cityName = addressComponent.getCity();
        String districtName = addressComponent.getDistrict();
        if (cityName.lastIndexOf("市") != -1 && districtName.lastIndexOf("区") != -1) {
            cityName = cityName.substring(0, cityName.lastIndexOf("市"));
            TbCityExample example = new TbCityExample();
            TbCityExample.Criteria criteria = example.createCriteria();
            criteria.andNameLike(cityName);  //模糊匹配城市
            int count = tbCityMapper.countByExample(example);
            if (count == 1) {
                Integer cityId = tbCityMapper.selectByExample(example).get(0).getId();
                if (cityId != null) {
                    TbDistrictExample  exampleTemp = new TbDistrictExample();
                    TbDistrictExample.Criteria criteriaTemp = exampleTemp.createCriteria();
                    criteriaTemp.andCityIdEqualTo(cityId);
                    criteriaTemp.andNameLike(districtName.substring(0, districtName.lastIndexOf("区")));
                    List<TbDistrict> tbDistrictList = tbDistrictMapper.selectByExample(exampleTemp);
                    if (CollectionUtils.isNotEmpty(tbDistrictList)) {
                        return tbDistrictList.get(0);
                    }
                }
            }
        }
        return null;
    }

    @Override
    public List<TbBizPlaceUnitSalePlan> getTbBizPlaceUnitSalePlanList(ReqPlaceSalePlan reqPlaceSalePlan) {
        TbBizPlaceUnitSalePlanExample tbBizPlaceUnitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
        tbBizPlaceUnitSalePlanExample.setOrderByClause(" place_unit_id ");
        TbBizPlaceUnitSalePlanExample.Criteria tbBizPlaceUnitSalePlanCriteria =
                tbBizPlaceUnitSalePlanExample.createCriteria();
        tbBizPlaceUnitSalePlanCriteria.andPlaceIdEqualTo(reqPlaceSalePlan.getPlaceId());
        tbBizPlaceUnitSalePlanCriteria.andIsEffectiveEqualTo(Constants.IS_EDITABLE_TRUE);
        tbBizPlaceUnitSalePlanCriteria.andCategoryIdEqualTo(reqPlaceSalePlan.getCategoryId());

        if (!StringUtils.isEmpty(reqPlaceSalePlan.getStartDate()) && !StringUtils.isEmpty(reqPlaceSalePlan.getEndDate())) {
            Date startDate = new Date(reqPlaceSalePlan.getStartDate().longValue());
            Date endDate = new Date(reqPlaceSalePlan.getEndDate().longValue());
            tbBizPlaceUnitSalePlanCriteria.andDateBetween(startDate, endDate);
            List<Integer> ids = reqPlaceSalePlan.getWeek();
            List<String> weeks = new ArrayList<String>();
            if (CollectionUtils.isEmpty(reqPlaceSalePlan.getWeek())) {
                String strweek = DateUtils.dayForWeek(DateUtils.transferDateToString(new Date()));

                switch (strweek) {
                    case "周一":
                        strweek = "1";
                        break;
                    case "周二":
                        strweek = "2";
                        break;
                    case "周三":
                        strweek = "3";
                        break;
                    case "周四":
                        strweek = "4";
                        break;
                    case "周五":
                        strweek = "5";
                        break;
                    case "周六":
                        strweek = "6";
                        break;
                    case "周日":
                        strweek = "7";
                        break;
                    default:
                        strweek = "1";
                }
                weeks.add(strweek);
            } else {
                for (Integer id : ids) {
                    weeks.add(id + "");
                }
            }
            tbBizPlaceUnitSalePlanCriteria.andTimeTypeIn(weeks);
        } else {
            Date startDate = new Date(reqPlaceSalePlan.getStartDate().longValue());
            tbBizPlaceUnitSalePlanCriteria.andDateEqualTo(startDate);
        }

        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = tbBizPlaceUnitSalePlanMapper
                .selectByExample(tbBizPlaceUnitSalePlanExample);
        return tbBizPlaceUnitSalePlanList;
    }

    @Override
    public RespPlaceUnitSalePlanDetail getSalePlanDetail(ReqPlaceSalePlan reqPlaceSalePlan, Integer from, List<TbBizPlaceUnitSalePlan> resultList) {

        Map map = this.placeUnitSalePlanMapper.getPlaceUnitTime(reqPlaceSalePlan.getPlaceId(),reqPlaceSalePlan.getCategoryId());
        RespPlaceUnitSalePlanDetail placeUnitSalePlanDetail = new RespPlaceUnitSalePlanDetail();
        placeUnitSalePlanDetail.setStartTime(MapUtils.getString(map, "startTime"));
        placeUnitSalePlanDetail.setEndTime(MapUtils.getString(map, "endTime"));

        Byte minSaleTimeUnit = Constants.BYTE_ONE;
        if (null != reqPlaceSalePlan.getCategoryId()){
            TbBizPlaceCategory placeCategory = this.getPlaceCategory(reqPlaceSalePlan.getPlaceId(), reqPlaceSalePlan.getCategoryId());
            if (!StringUtils.isEmpty(placeCategory)){
                minSaleTimeUnit = placeCategory.getMinSaleTimeUnit();
            }
        }
        if (null != minSaleTimeUnit && Constants.BYTE_ZERO == minSaleTimeUnit){
            placeUnitSalePlanDetail.setSplitTimeInterval(0.5d); // 半小时为单位拆分
        } else {
            placeUnitSalePlanDetail.setSplitTimeInterval(1d); // 默认1小时为单位
        }
        List<RespPlaceUnitSalePlanByDay> placeUnitInfoVoList = new ArrayList<>();

        TbBizPlaceRuleExample tbBizPlaceRuleExample = new TbBizPlaceRuleExample();
        TbBizPlaceRuleExample.Criteria tbBizPlaceRuleCriteria = tbBizPlaceRuleExample.createCriteria();
        tbBizPlaceRuleCriteria.andPlaceIdEqualTo(reqPlaceSalePlan.getPlaceId());
        List<TbBizPlaceRule> tbBizPlaceRuleList = tbBizPlaceRuleMapper.selectByExample(tbBizPlaceRuleExample);
        if (CollectionUtils.isEmpty(tbBizPlaceRuleList)) {
            placeUnitSalePlanDetail.setIsContainOtherDate(PlaceConstants.CONTAIN_OTHER_DATE);
        } else {
            placeUnitSalePlanDetail.setIsContainOtherDate(tbBizPlaceRuleList.get(0).getIsContainOtherDate());
        }
//        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = tbBizPlaceUnitSalePlanList = this.getTbBizPlaceUnitSalePlanList(reqPlaceSalePlan);
//        if (CollectionUtils.isEmpty(resultList) && from.intValue() == PlaceConstants.BILLING_TYPE){
//
//        }else {
//            List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanListInDB = this.getTbBizPlaceUnitSalePlanList(reqPlaceSalePlan);
//            if (CollectionUtils.isNotEmpty(tbBizPlaceUnitSalePlanListInDB)){
//                List<TbBizPlaceUnitSalePlan> subTractList = (List<TbBizPlaceUnitSalePlan>) org.apache.commons.collections.CollectionUtils.subtract(tbBizPlaceUnitSalePlanListInDB, resultList);
//                tbBizPlaceUnitSalePlanList.addAll(subTractList);
//            }else{
//                tbBizPlaceUnitSalePlanList = resultList;
//            }
//        }

        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList = this.getTbBizPlaceUnitSalePlanList(reqPlaceSalePlan);
        if (from.intValue() == PlaceConstants.PRIVATE_USE_TYPE){
            for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan1 : resultList){
                for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan2 :  tbBizPlaceUnitSalePlanList){
                    //todo 如果要支持半点   放开以下块注释   一定要压测
                    /*if (tbBizPlaceUnitSalePlan1.getSaleId().equals(tbBizPlaceUnitSalePlan2.getSaleId())){*/
                    if (tbBizPlaceUnitSalePlan1.getPlaceUnitId().intValue() == tbBizPlaceUnitSalePlan2.getPlaceUnitId().intValue()
                            && org.apache.commons.lang.time.DateUtils.isSameDay(tbBizPlaceUnitSalePlan1.getDate(),tbBizPlaceUnitSalePlan2.getDate())
                            && tbBizPlaceUnitSalePlan1.getStartTime().getTime()==(tbBizPlaceUnitSalePlan2.getStartTime().getTime())
                            && tbBizPlaceUnitSalePlan1.getEndTime().getTime() == (tbBizPlaceUnitSalePlan2.getEndTime().getTime())){
                        tbBizPlaceUnitSalePlan1.setStatus(tbBizPlaceUnitSalePlan2.getStatus());
                        tbBizPlaceUnitSalePlan1.setStartTime(tbBizPlaceUnitSalePlan2.getStartTime());
                        tbBizPlaceUnitSalePlan1.setEndTime(tbBizPlaceUnitSalePlan2.getEndTime());
                        tbBizPlaceUnitSalePlan1.setDate(tbBizPlaceUnitSalePlan2.getDate());
                        tbBizPlaceUnitSalePlan1.setPlaceId(tbBizPlaceUnitSalePlan2.getPlaceUnitId());
                        tbBizPlaceUnitSalePlan1.setDestSaleId(tbBizPlaceUnitSalePlan2.getDestSaleId());
                        tbBizPlaceUnitSalePlan1.setSaleId(tbBizPlaceUnitSalePlan2.getSaleId());
                  /*  // 还原代码
                    if (tbBizPlaceUnitSalePlan1.getSaleId().equals(tbBizPlaceUnitSalePlan2.getSaleId())){
                        tbBizPlaceUnitSalePlan1.setStatus(tbBizPlaceUnitSalePlan2.getStatus());*/




                        // 对于组合场地的还需要设置
                        if (PlaceConstants.UNIT_TYPE_COMBINE.equals(tbBizPlaceUnitSalePlan2.getUnitType())) {
                            tbBizPlaceUnitSalePlan1.setSubSaleplans(tbBizPlaceUnitSalePlan2.getSubSaleplans());
                        }
                    }
                }
            }
            tbBizPlaceUnitSalePlanList = resultList;
        }

        Map<String, RespPlaceUnitSalePlanByDay> respPlaceUnitSalePlanByDayMap = new HashMap<>();
        Map<String, RespPlaceUnitInfoVo> respPlaceUnitInfoVoMap = new LinkedHashMap<>();

        List<TbBizPlaceUnitSalePlan> releaseSalePlanList = new ArrayList<>();
        // todo...
        if (tbBizPlaceUnitSalePlanList != null && tbBizPlaceUnitSalePlanList.size() > 0) {
            for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
                String date = DateUtils.transferDateToString(tbBizPlaceUnitSalePlan.getDate());
                if (!respPlaceUnitSalePlanByDayMap.containsKey(date)) {//根据date区分RespPlaceUnitSalePlanByDay
                    RespPlaceUnitSalePlanByDay respPlaceUnitSalePlanByDay = new RespPlaceUnitSalePlanByDay();
                    respPlaceUnitSalePlanByDay.setDate(date);
                    respPlaceUnitSalePlanByDay.setWeek(DateUtils.dayForWeek(date));
                    respPlaceUnitSalePlanByDayMap.put(date, respPlaceUnitSalePlanByDay);
                    placeUnitInfoVoList.add(respPlaceUnitSalePlanByDay);
                }
                RespPlaceUnitSalePlanByDay respPlaceUnitSalePlanByDay = respPlaceUnitSalePlanByDayMap.get(date);

                if (respPlaceUnitSalePlanByDay.getPlaceUnitList() == null
                        || respPlaceUnitSalePlanByDay.getPlaceUnitList().size() <= 0) {
                    List<RespPlaceUnitInfoVo> respPlaceUnitInfoVoList = new ArrayList<>();
                    respPlaceUnitSalePlanByDay.setPlaceUnitList(respPlaceUnitInfoVoList);
                }

                List<RespPlaceUnitInfoVo> respPlaceUnitInfoVoList = respPlaceUnitSalePlanByDay.getPlaceUnitList();

                if (!respPlaceUnitInfoVoMap.containsKey(date + tbBizPlaceUnitSalePlan.getPlaceUnitId())) {
                    RespPlaceUnitInfoVo respPlaceUnitInfoVo = new RespPlaceUnitInfoVo();
                    RespPlaceUnitInfo respPlaceUnitInfo = new RespPlaceUnitInfo();
                    respPlaceUnitInfo.setId(tbBizPlaceUnitSalePlan.getPlaceUnitId());
                    respPlaceUnitInfo.setName(tbBizPlaceUnitSalePlan.getPlaceUnitName());//TODO 从数据库获取场地详情
                    respPlaceUnitInfoVo.setRespPlaceUnitInfo(respPlaceUnitInfo);
                    respPlaceUnitInfoVoMap.put(date + tbBizPlaceUnitSalePlan.getPlaceUnitId(), respPlaceUnitInfoVo);

                    respPlaceUnitInfoVoList.add(respPlaceUnitInfoVo);
                }
                RespPlaceUnitInfoVo respPlaceUnitInfoVo = respPlaceUnitInfoVoMap
                        .get(date + tbBizPlaceUnitSalePlan.getPlaceUnitId());

                if (respPlaceUnitInfoVo.getPlaceUnitSalePlanList() == null
                        || respPlaceUnitInfoVo.getPlaceUnitSalePlanList().size() <= 0) {
                    List<RespPlaceUnitSalePlanVo> placeUnitSalePlanList = new ArrayList<>();
                    respPlaceUnitInfoVo.setPlaceUnitSalePlanList(placeUnitSalePlanList);

                }

                List<RespPlaceUnitSalePlanVo> placeUnitSalePlanList = respPlaceUnitInfoVo.getPlaceUnitSalePlanList();

                RespPlaceUnitSalePlanVo respPlaceUnitSalePlanVo = new RespPlaceUnitSalePlanVo();

                RespPlaceUnitSalePlan respPlaceUnitSalePlan = new RespPlaceUnitSalePlan();

                if (PlaceConstants.PLACE_ORDER_STATUS.equals(tbBizPlaceUnitSalePlan.getStatus())||PlaceConstants.PLACE_LOCk_STATUS.equals(tbBizPlaceUnitSalePlan.getStatus())) {//锁定返回orderInfo
                    RespPlaceUserInfo userInfo = new RespPlaceUserInfo();
                    userInfo.setUid(tbBizPlaceUnitSalePlan.getOrderUid());

                    RespBizPlaceSalePlanOrderInfo orderInfo = new RespBizPlaceSalePlanOrderInfo();
                    //获取订单时间
                    TbBizPlaceOrderItemExample tbBizPlaceOrderItemExample = new TbBizPlaceOrderItemExample();
                    //tbBizPlaceOrderItemExample.createCriteria().andUnitSalePlanIdEqualTo(tbBizPlaceUnitSalePlan.getId());

                    //todo 如果要支持半点   放开以下块注释   一定要压测
                    /*if (from.intValue() == PlaceConstants.PRIVATE_USE_TYPE){
                        if (StringUtils.isEmpty(tbBizPlaceUnitSalePlan.getDestSaleId())){
                            if (!StringUtils.isEmpty(tbBizPlaceUnitSalePlan.getSaleId())){
                                List<String> saleIds = new ArrayList<>();
                                saleIds.add(tbBizPlaceUnitSalePlan.getSaleId());
                                saleIds.add(CommonUtils.createSaleID(tbBizPlaceUnitSalePlan.getPlaceUnitId(), tbBizPlaceUnitSalePlan.getDate(), tbBizPlaceUnitSalePlan.getStartTime(),null));
                                tbBizPlaceOrderItemExample.createCriteria().andSaleIdIn(saleIds);
                            }
                        } else {
                            List<String> saleIds = new ArrayList<>();
                            saleIds.add(CommonUtils.createSaleID(tbBizPlaceUnitSalePlan.getPlaceUnitId(), tbBizPlaceUnitSalePlan.getDate(), tbBizPlaceUnitSalePlan.getStartTime(),tbBizPlaceUnitSalePlan.getEndTime()));
                            saleIds.add(tbBizPlaceUnitSalePlan.getDestSaleId());
                            tbBizPlaceOrderItemExample.createCriteria().andSaleIdIn(saleIds);
                        }
                    }else if (from.intValue() == PlaceConstants.BILLING_TYPE){
                        if (StringUtils.isEmpty(tbBizPlaceUnitSalePlan.getDestSaleId())){
                            if (!StringUtils.isEmpty(tbBizPlaceUnitSalePlan.getSaleId())){
                                tbBizPlaceOrderItemExample.createCriteria().andSaleIdEqualTo(tbBizPlaceUnitSalePlan.getSaleId());
                            }
                        } else {
                            tbBizPlaceOrderItemExample.createCriteria().andSaleIdEqualTo(tbBizPlaceUnitSalePlan.getDestSaleId());
                        }
                    }*/
                    // 还原代码
                    if (StringUtils.isEmpty(tbBizPlaceUnitSalePlan.getDestSaleId())){
                        tbBizPlaceOrderItemExample.createCriteria().andSaleIdEqualTo(tbBizPlaceUnitSalePlan.getSaleId());
                    } else {
                        tbBizPlaceOrderItemExample.createCriteria().andSaleIdEqualTo(tbBizPlaceUnitSalePlan.getDestSaleId());
                    }

                    //tbBizPlaceOrderItemExample.createCriteria().andSaleIdEqualTo(tbBizPlaceUnitSalePlan.getSaleId());
                    List<TbBizPlaceOrderItem> tbBizPlaceOrderItems =
                            tbBizPlaceOrderItemMapper.selectByExample(tbBizPlaceOrderItemExample);
                    if (CollectionUtils.isNotEmpty(tbBizPlaceOrderItems)) {
//                        List<String> ids = new ArrayList<>();
//                        for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems){
//                            ids.add(tbBizPlaceOrderItem.getPlaceOrderId());
//                        }
                        TbBizPlaceOrderExample orderExample = new TbBizPlaceOrderExample();
                        
                        List<Byte> orderStatus = new ArrayList<>();
                        orderStatus.add(PlaceConstants.ORDER_COMPLETE_PAY_STATUS);
                        orderStatus.add(PlaceConstants.ORDER_PAYED_STATUS);
                        orderStatus.add(PlaceConstants.ORDER_PREPAY_STATUS);
                        orderStatus.add(PlaceConstants.ORDER_REFUNDING_STATUS);
                       /* if(from.intValue() == PlaceConstants.BILLING_TYPE){//开单

                        }else if(from.intValue() == PlaceConstants.PRIVATE_USE_TYPE){//包场
                            orderStatus.add(PlaceConstants.ORDER_PAYED_STATUS);
                        }*/
                        List<String> orderIds = new ArrayList<>();
                        for (TbBizPlaceOrderItem tbBizPlaceOrderItem: tbBizPlaceOrderItems){
                            orderIds.add(tbBizPlaceOrderItem.getPlaceOrderId());
                        }
                        orderExample.createCriteria().andPlaceOrderIdIn(orderIds).andOrderStatusIn(orderStatus);
//                                .andIsEffectiveEqualTo(PlaceConstants.YES);
                        List<TbBizPlaceOrder> tbBizPlaceOrders = tbBizPlaceOrderMapper.selectByExample(orderExample);
                        logger.debug("=======================tbBizPlaceOrders:{}",JSON.toJSON(tbBizPlaceOrders));
                        if (CollectionUtils.isNotEmpty(tbBizPlaceOrders)) {
                            TbBizPlaceOrder order = tbBizPlaceOrders.get(tbBizPlaceOrders.size()-1);
                            orderInfo.setOrderTime(order.getDate().getTime());
                            orderInfo.setOrderNo(order.getPlaceOrderId());
                            orderInfo.setSourceType(order.getSourceType());
                            orderInfo.setUseType(order.getUseType());
                            TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
                            tbBizPlacePayItemExample.createCriteria().andPlaceOrderIdEqualTo(order.getPlaceOrderId());
                            List<TbBizPlacePayItem> payItemList = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
                            if (CollectionUtils.isNotEmpty(payItemList)){
                                List<Integer> payTypeList = new ArrayList<>();
                                for (TbBizPlacePayItem tbBizPlacePayItem : payItemList){
                                    payTypeList.add(tbBizPlacePayItem.getPayType());
                                }
                                orderInfo.setPayTypeList(payTypeList);
                            }
                            TbBizPlaceOrderItemExample itemExample = new TbBizPlaceOrderItemExample();
                            TbBizPlaceOrderItemExample.Criteria itemCriteria = itemExample.createCriteria();
                            itemCriteria.andPlaceOrderIdEqualTo(order.getPlaceOrderId());
                            List<TbBizPlaceOrderItem> placeOrderItems = tbBizPlaceOrderItemMapper.selectByExample(itemExample);
                            BigDecimal orderPrice = new BigDecimal(0);
                            if (CollectionUtils.isNotEmpty(placeOrderItems)){
                                for (TbBizPlaceOrderItem tbBizPlaceOrderItem : placeOrderItems){
                                    orderPrice = orderPrice.add(isEmptyRetrunZero(tbBizPlaceOrderItem.getSalePrice()));
                                }
                            }
                            orderInfo.setOrderPrice(/*isEmptyRetrunZero(order.getDebit()).add(isEmptyRetrunZero(order.getCredit()))*/orderPrice);
                            orderInfo.setDescrible(order.getDescrible());
                            orderInfo.setIsMember(order.getIsMember());
                            orderInfo.setOrderStatus(order.getOrderStatus());

                            /*TbBizPlaceMemberOpHistoryExample tbBizPlaceMemberOpHistoryExample = new TbBizPlaceMemberOpHistoryExample();
                            tbBizPlaceMemberOpHistoryExample.createCriteria().andOrderNoEqualTo(order.getPlaceOrderId());
                            List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistoryList = tbBizPlaceMemberOpHistoryMapper.selectByExample(tbBizPlaceMemberOpHistoryExample);
                            if (CollectionUtils.isNotEmpty(tbBizPlaceMemberOpHistoryList)){
                                orderInfo.setMemberCardName(tbBizPlaceMemberOpHistoryList.get(0).getCardTypeName());
                            }*/
                            if (!StringUtils.isEmpty(order.getInnerCardNo())){
                                TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
                                tbBizPlaceMemberCardExample.createCriteria().andInnerCardNoEqualTo(order.getInnerCardNo());
                                List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = tbBizPlaceMemberCardMapper.selectByExample(tbBizPlaceMemberCardExample);
                                if (CollectionUtils.isNotEmpty(tbBizPlaceMemberCardList)){
                                    orderInfo.setMemberCardName(tbBizPlaceMemberCardList.get(0).getCardName());
                                }
                            }

                            userInfo.setNickName(order.getCustomerName());
                            userInfo.setMobile(order.getMobile());
//                            if (StringUtils.isEmpty(tbBizPlaceOrders.get(0).getParentId())){
//                                TbBizPlaceOrder order = tbBizPlaceOrders.get(0);
//                                orderInfo.setOrderTime(order.getCreateTime().getTime());
//                                orderInfo.setOrderNo(order.getPlaceOrderId());
//                                orderInfo.setSourceType(order.getSourceType());
//                                orderInfo.setOrderPrice(isEmptyRetrunZero(order.getDebit()).add(isEmptyRetrunZero(order.getCredit())));
//                                orderInfo.setDescrible(order.getDescrible());
//                                userInfo.setNickName(order.getCustomerName());
//                                userInfo.setMobile(order.getMobile());
//                            } else {
//                                TbBizPlacePrivateOrder tbBizPlacePrivateOrder = tbBizPlacePrivateOrderMapper.selectByPrimaryKey(tbBizPlaceOrders.get(0).getParentId());
//                                orderInfo.setOrderTime(tbBizPlacePrivateOrder.getCreateTime().getTime());
//                                orderInfo.setOrderNo(tbBizPlacePrivateOrder.getPlaceOrderId());
//                                orderInfo.setSourceType(tbBizPlacePrivateOrder.getSourceType());
//                                orderInfo.setOrderPrice(isEmptyRetrunZero(tbBizPlacePrivateOrder.getDebit()).add(isEmptyRetrunZero(tbBizPlacePrivateOrder.getCredit())));
//                                orderInfo.setDescrible(tbBizPlacePrivateOrder.getDescrible());
//                                orderInfo.setOrderType(1);//包场父订单标志
//                                if (!StringUtils.isEmpty(tbBizPlacePrivateOrder.getStartDate()) &&
//                                        !StringUtils.isEmpty(tbBizPlacePrivateOrder.getEndDate()) &&
//                                        !StringUtils.isEmpty(tbBizPlacePrivateOrder.getWeeks())) {
//                                    orderInfo.setStarDate(DateTimeUtils.convertDate2String("yyyy-MM-dd",tbBizPlacePrivateOrder.getStartDate()));
//                                    orderInfo.setEndDate(DateTimeUtils.convertDate2String("yyyy-MM-dd",tbBizPlacePrivateOrder.getEndDate()));
//                                    orderInfo.setWeeks(tbBizPlacePrivateOrder.getWeeks());
//                                }
//                                userInfo.setNickName(tbBizPlacePrivateOrder.getCustomerName());
//                                userInfo.setMobile(tbBizPlacePrivateOrder.getMobile());
//                            }
                        }else {
                            //销售计划状态异常，异步修改下销售计划状态
                            releaseSalePlanList.add(tbBizPlaceUnitSalePlan);
                        }
                    } else {
                        //销售计划状态异常，异步修改下销售计划状态
                        releaseSalePlanList.add(tbBizPlaceUnitSalePlan);
                    }
                    orderInfo.setUserInfo(userInfo);
                    respPlaceUnitSalePlanVo.setOrderInfo(orderInfo);
                    logger.debug("+++++++++++++++++订单{}",JSON.toJSON(orderInfo));
                }

                /*try {
                    BeanUtils.copyProperties(tbBizPlaceUnitSalePlan, respPlaceUnitSalePlan);
                    respPlaceUnitSalePlanVo.setRespPlaceUnitSalePlan(respPlaceUnitSalePlan);

                } catch (Exception e) {
                    logger.error("reqPlaceSalePlan:{}, error:{}", JSON.toJSONString(reqPlaceSalePlan), e);
                }*/
                respPlaceUnitSalePlan.setStartTime(DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getStartTime()));
                respPlaceUnitSalePlan.setEndTime(DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getEndTime()));
                respPlaceUnitSalePlan.setPlaceId(tbBizPlaceUnitSalePlan.getPlaceId());
                respPlaceUnitSalePlan.setPlaceUnitId(tbBizPlaceUnitSalePlan.getPlaceUnitId());
                respPlaceUnitSalePlan.setSaleId(tbBizPlaceUnitSalePlan.getSaleId());
                respPlaceUnitSalePlan.setPrice(tbBizPlaceUnitSalePlan.getPrice());
                respPlaceUnitSalePlan.setStatus(tbBizPlaceUnitSalePlan.getStatus());
                respPlaceUnitSalePlan.setDate(DateUtils.transferDateToString(tbBizPlaceUnitSalePlan.getDate()));
                respPlaceUnitSalePlan.setMemberPrice(tbBizPlaceUnitSalePlan.getMemberPrice());
                respPlaceUnitSalePlan.setLowestPrice(tbBizPlaceUnitSalePlan.getLowestPrice());
                respPlaceUnitSalePlan.setLockRemarks(tbBizPlaceUnitSalePlan.getLockRemark());
                respPlaceUnitSalePlan.setOperateTime(tbBizPlaceUnitSalePlan.getLockTime());
                if (!StringUtils.isEmpty(tbBizPlaceUnitSalePlan.getOrderUid())){
                    TbAdminUser tbAdminUser = tbAdminUserMapper.selectByPrimaryKey(tbBizPlaceUnitSalePlan.getOrderUid());
                    if (!StringUtils.isEmpty(tbAdminUser)) {
                        respPlaceUnitSalePlan.setOpertator(tbAdminUser.getTrueName());
                    } else {
                        //线上操作人
                        respPlaceUnitSalePlan.setOpertator("未知");
                        try{
                            APIResponse<RespUserInfoBase> userResponse = userServiceFacade.queryUserInfo(tbBizPlaceUnitSalePlan.getCreateUid());
                            if (userResponse.isRet()) {
                                if (!StringUtils.isEmpty(userResponse.getData())) {
                                    if (!StringUtils.isEmpty(userResponse.getData().getNickName())) {
                                        respPlaceUnitSalePlan.setOpertator(userResponse.getData().getNickName());
                                    }
                                }
                            }
                        }catch (Exception e){
                            logger.error("调用用户中心异常");
                        }
                    }
                }

                respPlaceUnitSalePlanVo.setRespPlaceUnitSalePlan(respPlaceUnitSalePlan);
                placeUnitSalePlanList.add(respPlaceUnitSalePlanVo);
            }
        }

        placeUnitSalePlanDetail.setPlaceUnitInfoVoList(placeUnitInfoVoList);

        // fix 一下组合场地的影响
        pucService.fixPlaceUnitSalePlanDetail(placeUnitSalePlanDetail, tbBizPlaceUnitSalePlanList);

        //销售计划状态异常，异步修改下销售计划状态
        placeOrderUtilService.releaseSalePlanStatus(releaseSalePlanList);

        return placeUnitSalePlanDetail;
    }

    private BigDecimal isEmptyRetrunZero(BigDecimal bigDecimal){
        if(StringUtils.isEmpty(bigDecimal)){
            bigDecimal = new BigDecimal(0.00);
        }
        return bigDecimal;
    }

    /**
     * 根据场馆id和运动项目查询场馆项目配置
     * @param placeId
     * @param categoryId
     * @return
     */
    public TbBizPlaceCategory getPlaceCategory(Integer placeId, Integer categoryId) {
        TbBizPlaceCategoryExample tbBizPlaceCategoryExample = new TbBizPlaceCategoryExample();
        TbBizPlaceCategoryExample.Criteria tbBizPlaceCategoryCriteria = tbBizPlaceCategoryExample.createCriteria();
        tbBizPlaceCategoryCriteria.andPlaceIdEqualTo(placeId);
        tbBizPlaceCategoryCriteria.andCategoryIdEqualTo(categoryId);
        List<TbBizPlaceCategory> tbBizPlaceCategoryList = tbBizPlaceCategoryMapper.selectByExample(tbBizPlaceCategoryExample);
        if (null != tbBizPlaceCategoryList && tbBizPlaceCategoryList.size() > 0){
            return tbBizPlaceCategoryList.get(0);
        }
        return null;
    }

    @Override
    public List<TbBizPlaceUnitTime> getTbBizPlaceUnitTimes(@NotNull(message = "场馆ID不能为空") Integer placeId) {
        TbBizPlaceUnitTimeExample tbBizPlaceUnitTimeExample = new TbBizPlaceUnitTimeExample();
        TbBizPlaceUnitTimeExample.Criteria criteria = tbBizPlaceUnitTimeExample.createCriteria();
        criteria.andPlaceIdEqualTo(placeId);
        List<TbBizPlaceUnitTime> tbBizPlaceUnitTimes = tbBizPlaceUnitTimeMapper.selectByExample(tbBizPlaceUnitTimeExample);
        if (StringUtils.isEmpty(tbBizPlaceUnitTimes)) {
            return null;
        }
        return tbBizPlaceUnitTimes;
    }

    @Override
    public boolean updateTbBizPlaceUnitSalePlan(List<String> placeUnitIds, Byte state, String lockRemarks) {
        if (CollectionUtils.isEmpty(placeUnitIds) || StringUtils.isEmpty(state)) {
            return false;
        }
        //只有空闲的场地才能锁定，锁定的场地才能解锁
        TbBizPlaceUnitSalePlanExample tbBizPlaceUnitSalePlanExample1 = new TbBizPlaceUnitSalePlanExample();
        tbBizPlaceUnitSalePlanExample1.createCriteria().andSaleIdIn(placeUnitIds);
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(tbBizPlaceUnitSalePlanExample1);
        List<String> ids = new ArrayList<>();
        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlans){
            if(tbBizPlaceUnitSalePlan.getStatus().intValue() == PlaceConstants.PLACE_PREORDER_STATUS.intValue()
                    || tbBizPlaceUnitSalePlan.getStatus().intValue() == PlaceConstants.PLACE_BACKGROUND_STATUS.intValue()){
                ids.add(tbBizPlaceUnitSalePlan.getSaleId());
            }
        }
        int flag = 0;
        TbBizPlaceUnitSalePlanExample tbBizPlaceUnitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
        if (CollectionUtils.isNotEmpty(ids)){
            tbBizPlaceUnitSalePlanExample.createCriteria().andSaleIdIn(ids);
            TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan = new TbBizPlaceUnitSalePlan();
            tbBizPlaceUnitSalePlan.setStatus(state);
            tbBizPlaceUnitSalePlan.setLockRemark(lockRemarks);
            flag = this.tbBizPlaceUnitSalePlanMapper.updateByExampleSelective(tbBizPlaceUnitSalePlan,
                    tbBizPlaceUnitSalePlanExample);
        }
        return flag != 0;
    }

    @Override
    public boolean updateTbBizPlaceUnitSalePlanEx(List<String> placeUnitIds, Byte state, String lockRemarks,String uid){
        if (CollectionUtils.isEmpty(placeUnitIds) || StringUtils.isEmpty(state)) {
            return false;
        }

        TbBizPlaceUnitSalePlanExample tbBizPlaceUnitSalePlanExample1 = new TbBizPlaceUnitSalePlanExample();
        tbBizPlaceUnitSalePlanExample1.createCriteria().andSaleIdIn(placeUnitIds);
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this.tbBizPlaceUnitSalePlanMapper.selectByExample(tbBizPlaceUnitSalePlanExample1);

        if (tbBizPlaceUnitSalePlans == null
                || tbBizPlaceUnitSalePlans.size() <= 0) {
            return false;
        }

        // 需要判断组合和基本销售计划间没有"重叠"
        APIResponse apiResponse = this.salePlansVerification(tbBizPlaceUnitSalePlans);
        if (apiResponse != null) {
            return false;
        }

        return updateTbBizPlaceUnitSalePlanBatch(tbBizPlaceUnitSalePlans, state, lockRemarks,uid);
    }


    public boolean updateTbBizPlaceUnitSalePlanBatch(List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans, Byte state, String lockRemarks,String uid) {
        for (TbBizPlaceUnitSalePlan tbSalePlan : tbBizPlaceUnitSalePlans) {
            boolean flag = updateTbBizPlaceUnitSalePlanSingle(tbSalePlan, state, lockRemarks,uid);
            if (!flag) {
                return false;
            }
        }

        return true;
    }

    // 锁定单个场地
    public boolean updateTbBizPlaceUnitSalePlanSingle(TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan, Byte state, String lockRemarks,String uid) {
        List<String> ids = new ArrayList<>();

        // 只有空闲的场地才能锁定，锁定的场地才能解锁
        if(tbBizPlaceUnitSalePlan.getStatus().intValue() == PlaceConstants.PLACE_PREORDER_STATUS.intValue()
                || tbBizPlaceUnitSalePlan.getStatus().intValue() == PlaceConstants.PLACE_BACKGROUND_STATUS.intValue()){
            ids.add(tbBizPlaceUnitSalePlan.getSaleId());
        } else {
            return false;
        }

        Byte srcStatus = tbBizPlaceUnitSalePlan.getStatus();

        // 如果是组合场通过销售计划状态判断
        Boolean canOperate = true;
        if (UNIT_TYPE_COMBINE.equals(tbBizPlaceUnitSalePlan.getUnitType())) {
            String subSalePlans = tbBizPlaceUnitSalePlan.getSubSaleplans();
            List<String> subSaleplanIds = new ArrayList<>();
            if (subSalePlans != null) {
                subSaleplanIds = Arrays.asList(subSalePlans.split("[|]"));
            }

            // 要去查数据库
            Map<String, TbBizPlaceUnitSalePlan> salePlansMap = getSalePlans(subSaleplanIds);
            for (String salePlanId : subSaleplanIds) {
                TbBizPlaceUnitSalePlan tbSubSalePlan = salePlansMap.get(salePlanId);
                if (tbSubSalePlan == null) {
                    canOperate = false;
                    break;
                }

                // 只有空闲的场地才能锁定，锁定的场地才能解锁
                if (!srcStatus.equals(tbSubSalePlan.getStatus())) {
                    canOperate = false;
                    break;
                }
            }

            if (!canOperate) {
                return false;
            }
            ids.addAll(subSaleplanIds);
        }

        int flag = 0;
        TbBizPlaceUnitSalePlanExample tbBizPlaceUnitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
        if (CollectionUtils.isNotEmpty(ids)){
            tbBizPlaceUnitSalePlanExample.createCriteria().andSaleIdIn(ids);
            TbBizPlaceUnitSalePlan updatePlaceUnitSalePlan = new TbBizPlaceUnitSalePlan();
            updatePlaceUnitSalePlan.setStatus(state);
            updatePlaceUnitSalePlan.setLockRemark(StringUtil.isBlankOrNull(lockRemarks)?"无":lockRemarks);
            updatePlaceUnitSalePlan.setLockTime(new Date());
            updatePlaceUnitSalePlan.setOrderUid(Integer.parseInt(uid));
            flag = this.tbBizPlaceUnitSalePlanMapper.updateByExampleSelective(updatePlaceUnitSalePlan,
                    tbBizPlaceUnitSalePlanExample);
        }

        return (flag == ids.size());
    }

    // key -> salePlanMain
    public Map<String, TbBizPlaceUnitSalePlan> getSalePlans(List<String> saleIds) {
        Map<String, TbBizPlaceUnitSalePlan> result = new HashMap<>();


        TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
        TbBizPlaceUnitSalePlanExample.Criteria criterial = example.createCriteria();
        criterial.andSaleIdIn(saleIds);

        List<TbBizPlaceUnitSalePlan> salePlans = tbBizPlaceUnitSalePlanMapper.selectByExample(example);
        if (salePlans != null && salePlans.size() > 0) {
            for (TbBizPlaceUnitSalePlan salePlan : salePlans) {
                result.put(salePlan.getSaleId(), salePlan);
            }
        }

        return result;
    }

    @Override
    public String getBizOrderId(Integer uid) {
        /*SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
        String orderId = sd.format(new Date());
        orderId += new Date().getTime() +
                org.apache.commons.lang3.StringUtils.leftPad(new Random().nextInt(100)+"", 3, "0");
        return orderId;*/
        return CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, uid);
    }

    @Override
    public boolean saveTbBizPlaceOrder(TbBizPlaceOrder tbBizPlaceOrder) {
        int flag = this.tbBizPlaceOrderMapper.insert(tbBizPlaceOrder);
        return flag != 0;
    }

    @Override
    public boolean saveTbBizpPlaceOrderItem(TbBizPlaceOrderItem tbBizPlaceOrderItem) {
        int flag = this.tbBizPlaceOrderItemMapper.insert(tbBizPlaceOrderItem);
        return flag != 0;
    }

    /**
     * 支付后修改销售计划状态
     * @param tbBizPlaceOrderItems
     */
    public void placeBillingUpdatePlaceUnitSalePlan(List<TbBizPlaceOrderItem> tbBizPlaceOrderItems,byte status){
        List<String> ids = new ArrayList<String>();
        for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems) {
            ids.add(tbBizPlaceOrderItem.getSaleId());
        }
        TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
        example.createCriteria().andSaleIdIn(ids);
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = tbBizPlaceUnitSalePlanMapper
                .selectByExample(example);
        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)){
            return;
        }
        List<UnitSalePlan> list = new ArrayList<UnitSalePlan>();
        for (TbBizPlaceUnitSalePlan tsp : tbBizPlaceUnitSalePlans) {
            UnitSalePlan up = new UnitSalePlan();
            up.setSaleId(tsp.getSaleId());
            list.add(up);
        }
        ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
        reqPlaceOrderListVo.setUnitSalePlanIdList(list);
        reqPlaceOrderListVo.setStatus(status);//预订——>销售计划状态改成已预订
        //placeUnitSalePlanMapper.updateByPrimaryKeyList(reqPlaceOrderListVo);
        this.updateSalePlanByPrimaryKeyList(reqPlaceOrderListVo);
    }

    public List<TbBizPlaceOrderItem> salePlans2OrderItem(List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans,
                                                         Integer uid, String orderid, int method,ReqBillingInfo reqBillingInfo,
                                                         int useType) {
        List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = new ArrayList<TbBizPlaceOrderItem>();
        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlans) {
            TbBizPlaceOrderItem tbBizPlaceOrderItem = new TbBizPlaceOrderItem();
            tbBizPlaceOrderItem.setPlaceOrderId(orderid);
            tbBizPlaceOrderItem.setUnitSalePlanId(tbBizPlaceUnitSalePlan.getId());
            tbBizPlaceOrderItem.setVersion(tbBizPlaceUnitSalePlan.getVersion());
            tbBizPlaceOrderItem.setSaleId(tbBizPlaceUnitSalePlan.getSaleId());
            if(method == PlaceConstants.PRIVATE_USE_TYPE){//包场取会员价
                tbBizPlaceOrderItem.setSalePrice(tbBizPlaceUnitSalePlan.getMemberPrice());
            }else if(method == PlaceConstants.BILLING_TYPE){//开单
                tbBizPlaceOrderItem.setSalePrice(tbBizPlaceUnitSalePlan.getPrice());
            }
            tbBizPlaceOrderItem.setCreateUid(uid);
            tbBizPlaceOrderItem.setConsumeTime(tbBizPlaceUnitSalePlan.getDate());//消费日期
            tbBizPlaceOrderItem.setItemUuid(UUIDUtils.createId());
            tbBizPlaceOrderItem.setUseType((byte)useType);
            tbBizPlaceOrderItem.setGoodsId(tbBizPlaceUnitSalePlan.getId());
            tbBizPlaceOrderItem.setGoodsName(tbBizPlaceUnitSalePlan.getPlaceUnitName());
            tbBizPlaceOrderItem.setSurplusGoodsCount(1);
            tbBizPlaceOrderItem.setTotalGoodsCount(1);
            tbBizPlaceOrderItem.setStartTime(tbBizPlaceUnitSalePlan.getStartTime());
            tbBizPlaceOrderItem.setEndTime(tbBizPlaceUnitSalePlan.getEndTime());
            tbBizPlaceOrderItem.setOriginPrice(tbBizPlaceUnitSalePlan.getPrice());
            tbBizPlaceOrderItem.setMemberPrice(tbBizPlaceUnitSalePlan.getMemberPrice());
            tbBizPlaceOrderItems.add(tbBizPlaceOrderItem);
        }
        return tbBizPlaceOrderItems;
    }

    @Override
    public TbBizPlaceUnitSalePlan getNotSellPlan(List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans) {
        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlans) {
            if (tbBizPlaceUnitSalePlan.getStatus().intValue() == PlaceConstants.PLACE_PREORDER_STATUS
                    || tbBizPlaceUnitSalePlan.getStatus().intValue() == PlaceConstants.PLACE_BACKGROUND_STATUS) {
                continue;
            } else {
                return tbBizPlaceUnitSalePlan;
            }
        }
        return null;
    }

    @Override
    public PageObj<List<RespUserBizPlaceOrderInfo>> getRespBizPlaceOrderInfoByUid(String mobile, Integer uid,
                                                                                  Integer pageNum, Integer pageSize,
                                                                                  Integer opType, Integer sourceType,
                                                                                  Integer orderStatus, Integer isEnable) {
        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria criteria = tbBizPlaceOrderExample.createCriteria();
        if (!StringUtils.isEmpty(mobile)) {
            criteria.andMobileEqualTo(mobile);
        }
        if (!StringUtils.isEmpty(uid)) {
            criteria.andUidEqualTo(uid);
        }
        if (!StringUtils.isEmpty(sourceType)) {
            criteria.andSourceTypeEqualTo((byte) sourceType.intValue());
            if (sourceType.intValue() == 3 || sourceType.intValue() == 4){
                criteria.andOrderUseEqualTo(Constants.IS_EDITABLE_FALSE);
            }
        }
        if (!StringUtils.isEmpty(orderStatus)){
            criteria.andOrderStatusEqualTo(Byte.valueOf(orderStatus + ""));
        }

        criteria.andIsEffectiveEqualTo(PlaceConstants.IS_EFFECTIVE_YES);
        //商品目前不展示在APP上
//        criteria.andUseTypeNotEqualTo(PlaceConstants.ORDER_USE_GOODS);
        // 门票 、app开单显示在APP上
        List list = new ArrayList();
        list.add(PlaceConstants.ORDER_USE_TICKET);
        list.add(PlaceConstants.ORDER_USE_APP_BILLING);
        criteria.andUseTypeIn(list);

        tbBizPlaceOrderExample.setOrderByClause(" create_time desc");
        int total = tbBizPlaceOrderMapper.countByExample(tbBizPlaceOrderExample);
        if (0 == total) {
            return null;
        }
        tbBizPlaceOrderExample.setPage(new Page(pageNum * pageSize, pageSize, total));
        List<TbBizPlaceOrder> tbBizPlaceOrders = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);

        if (CollectionUtils.isEmpty(tbBizPlaceOrders)) {
            return null;
        }

        List<RespUserBizPlaceOrderInfo> respUserBizPlaceOrderInfos =
                tbBizPlaceOrders2RespBizPlaceOrderInfos(tbBizPlaceOrders, opType, orderStatus, isEnable);
        PageObj<List<RespUserBizPlaceOrderInfo>> pageObj =
                PageObj.create(total, pageNum, pageSize, respUserBizPlaceOrderInfos);
        return pageObj;
    }

    @Override
    public PlaceIndexInfo tb2InsertPlaceIndexInfo(@NotNull(message = "场馆对象不能为空") TbBizPlace tbBizPlace) {
        PlaceIndexInfo insertPlaceIndexInfo = new PlaceIndexInfo();
        insertPlaceIndexInfo.setPlace_id(tbBizPlace.getId().toString());
        insertPlaceIndexInfo.setPlace_name(tbBizPlace.getName());
        List<TbBizPlaceCategory> tbBizPlaceCategories = getTbBizPlaceCategoryByPlaceId(tbBizPlace.getId());
        if (CollectionUtils.isEmpty(tbBizPlaceCategories)) {
//            return null;
        }
        Map<Integer, String> categoryMap = getSysCategoryMap();
        if (StringUtils.isEmpty(categoryMap)) {
//            return null;
        }
        List<Integer> categoryId = new ArrayList<>();
        List<String> categoryName = new ArrayList<>();
        for (TbBizPlaceCategory tbBizPlaceCategory : tbBizPlaceCategories) {
            categoryId.add(tbBizPlaceCategory.getCategoryId());
            categoryName.add(categoryMap.get(tbBizPlaceCategory.getCategoryId()));
        }
        insertPlaceIndexInfo.setPlace_categoryId(categoryId);
        insertPlaceIndexInfo.setPlace_categoryName(categoryName);

        TbCity tbCity = this.tbCityMapper.selectByPrimaryKey(tbBizPlace.getCityId());
        if (null != tbCity){
            if (null != tbCity.getName()){
                insertPlaceIndexInfo.setPlace_cityName(tbCity.getName());
            }
            if (null != tbCity.getId()){
                insertPlaceIndexInfo.setPlace_cityId(tbCity.getId());
            }
        }

        TbDistrict tbDistrict = this.tbDistrictMapper.selectByPrimaryKey(tbBizPlace.getDistrictId());
        if (null != tbDistrict){
            if (null != tbDistrict.getName()){
                insertPlaceIndexInfo.setPlace_districtName(tbDistrict.getName());
            }
            if (null != tbDistrict.getId()){
                insertPlaceIndexInfo.setPlace_districtId(tbDistrict.getId());
            }

        }
        if (null != tbBizPlace){
            insertPlaceIndexInfo.setPlace_lat(tbBizPlace.getLat());
            insertPlaceIndexInfo.setPlace_lng(tbBizPlace.getLng());
            insertPlaceIndexInfo.setPlace_commentCount(tbBizPlace.getCommentCount());
            insertPlaceIndexInfo.setPlace_signupCount(tbBizPlace.getSignupCount());
            insertPlaceIndexInfo.setPlace_placeScore(tbBizPlace.getPlaceScore());
            insertPlaceIndexInfo.setPlace_lowestPrice(tbBizPlace.getLowestPrice());
            insertPlaceIndexInfo.setPlace_bizPlaceUrl(tbBizPlace.getBizPlaceUrl());
            insertPlaceIndexInfo.setPlace_groupId(tbBizPlace.getGroupId());
            insertPlaceIndexInfo.setPlace_address(tbBizPlace.getAddress());
        }



        TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(tbBizPlace.getId());
        if (null != placeAttach && org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getBookingConsultPhone())){
            insertPlaceIndexInfo.setPlace_phone(placeAttach.getBookingConsultPhone());
            insertPlaceIndexInfo.setPlace_isVip(placeAttach.getIsVip().intValue());
        } else {
            // 获取系统配置的百灵鸟客服热线
            TbCommonParameter parameterVo = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
            if (null != parameterVo){
                insertPlaceIndexInfo.setPlace_phone(parameterVo.getParameterValue());
            }
        }
        insertPlaceIndexInfo.setPlace_name(tbBizPlace.getName());
        insertPlaceIndexInfo.setPlace_isShelves(tbBizPlace.getIsShelves());

        // 场馆名称首字母
        String pinyins = PinYinUtils.converterToFirstSpell(tbBizPlace.getName());
        if (!StringUtils.isEmpty(pinyins)){
           String[] tmpPinyin = org.apache.commons.lang3.StringUtils.split(pinyins, ",");
           List<String> pinyinList = Arrays.asList(tmpPinyin);
            insertPlaceIndexInfo.setPlace_initials(pinyinList);
        }
        if(tbBizPlace.getIsSign() != null){
            insertPlaceIndexInfo.setPlace_isSigned(Integer.parseInt(tbBizPlace.getIsSign() + ""));
        }else{
            insertPlaceIndexInfo.setPlace_isSigned(Integer.parseInt(PlaceConstants.IS_SIGN_NO + ""));
        }

        return insertPlaceIndexInfo;
    }

    public Map<Integer, TbBizPlaceCategory> getLPriceMap(Integer placeid){
        List<TbBizPlaceCategory> tbBizPlaceCategories = placeUnitSalePlanMapper.getLPriceByPlaceId(placeid);
        if (CollectionUtils.isNotEmpty(tbBizPlaceCategories)){
            Map<Integer, TbBizPlaceCategory> map = new HashMap<>();
            for (TbBizPlaceCategory tbBizPlaceCategory : tbBizPlaceCategories){
                map.put(tbBizPlaceCategory.getId(), tbBizPlaceCategory);
            }
            return map;
        }
        return null;
    }

    public Map<Integer, Double>  getLPrice(Integer placeId){
        PlaceUnitSalePlan placeUnitSalePlan = new PlaceUnitSalePlan();
        placeUnitSalePlan.setPlaceId(placeId);
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlenList = placeUnitSalePlanMapper.getBizPlaceMinPrice(placeUnitSalePlan);
        if (CollectionUtils.isNotEmpty(tbBizPlaceUnitSalePlenList)){
            Map<Integer,Double> prices = new HashMap<>();
            for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlenList){
                if(!StringUtils.isEmpty(tbBizPlaceUnitSalePlan.getPrice())){
                    prices.put(tbBizPlaceUnitSalePlan.getCategoryId(),tbBizPlaceUnitSalePlan.getPrice().doubleValue());
                }
            }
            return prices;
        }
        return null;
    }

    @Override
    public List<TbBizPlaceOrderItem> adjustOrderItemPrice(BigDecimal receivedAmount,List<TbBizPlaceOrderItem> tbBizPlaceOrderItems,BigDecimal totalSalePrice) {
        List<TbBizPlaceOrderItem> list = new ArrayList<TbBizPlaceOrderItem>();
        //下标
        int index = 0;
        //最后一个场地之前的场地优惠总金额
        BigDecimal lastBeforeAmount = new BigDecimal(0);
        for (TbBizPlaceOrderItem item : tbBizPlaceOrderItems){
            index ++;
            if (index == tbBizPlaceOrderItems.size()){
            	item.setAdjustPrice(item.getSalePrice().subtract(receivedAmount.subtract(lastBeforeAmount)));
                item.setSalePrice(receivedAmount.subtract(lastBeforeAmount));
            }else{
        	    BigDecimal salePrice = item.getSalePrice().multiply(receivedAmount).divide(totalSalePrice,2,BigDecimal.ROUND_HALF_UP);
                item.setAdjustPrice(item.getSalePrice().subtract(salePrice));
                item.setSalePrice(salePrice);
                lastBeforeAmount = lastBeforeAmount.add(item.getSalePrice());
            }
            list.add(item);
        }
        return list;
    }

    public List<PlaceIndexInfo> getPlaceSalePlanSerach(
            @NotNull(message = "场馆对象不能为空") TbBizPlace tbBizPlace,
            Integer days, PlaceIndexInfo placeIndexInfo1) {
        List<PlaceIndexInfo> placeIndexInfos = new ArrayList<>();
        try {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sf1 = new SimpleDateFormat("HH:mm:ss");
        SimpleDateFormat sf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans =
                    this.getTbBizPlaceUnitSalePlansByPlaeId(tbBizPlace.getId() ,days);
            if (CollectionUtils.isNotEmpty(tbBizPlaceUnitSalePlans)){
                Map<Integer, Double> map = getLPrice(tbBizPlace.getId());

                for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlans) {
//                    TbBizPlaceCategoryExample example = new TbBizPlaceCategoryExample();
//                    example.createCriteria().andPlaceIdEqualTo(tbBizPlace.getId()).andCategoryIdEqualTo(tbBizPlaceUnitSalePlan.getCategoryId());
//                    List<TbBizPlaceCategory> list = tbBizPlaceCategoryMapper.selectByExample(example);
//                    if (CollectionUtils.isNotEmpty(list)){
//                        placeIndexInfo1.setPlace_lowestPrice(list.get(0).getLowestPrice());
//                    }
                    if (!StringUtils.isEmpty(map)) {
                        placeIndexInfo1.setPlace_lowestPrice(map.get(tbBizPlaceUnitSalePlan.getCategoryId()));
                    }

                    PlaceIndexInfo placeIndexInfo = new PlaceIndexInfo();
                    BeanUtils.copyProperties(placeIndexInfo1, placeIndexInfo);
                    placeIndexInfo.setPlace_salePlanId(tbBizPlaceUnitSalePlan.getId() + "");
                    String date = sf.format(tbBizPlaceUnitSalePlan.getDate());
                    String start = sf1.format(tbBizPlaceUnitSalePlan.getStartTime());
                    String end = sf1.format(tbBizPlaceUnitSalePlan.getEndTime());
                    if(StringUtils.isEmpty(date) || StringUtils.isEmpty(start) || StringUtils.isEmpty(end)){
                        continue;
                    }
                    placeIndexInfo.setPlace_startTime(sf2.parse(date + " " + start));
                    placeIndexInfo.setPlace_endTime(sf2.parse(date + " " + end));
                    placeIndexInfo.setPlace_isSaled(Integer.parseInt(tbBizPlaceUnitSalePlan.getStatus() + ""));
                    if (tbBizPlaceUnitSalePlan.getStatus().intValue() == PlaceConstants.PLACE_PREORDER_STATUS){
                        placeIndexInfo.setPlace_isSaled(2); //2 可以售卖
                    }else {
                        placeIndexInfo.setPlace_isSaled(1);// 1 不可售卖
                    }
                    placeIndexInfo.setPlace_categoryIdSingle(tbBizPlaceUnitSalePlan.getCategoryId());
                    placeIndexInfos.add(placeIndexInfo);
                }
            }else {
                placeIndexInfo1.setPlace_isSaled(0);//0没有销售计划
                placeIndexInfos.add(placeIndexInfo1);
            }
        } catch (ParseException e) {
            logger.error("解析销售计划时间错误:{}", tbBizPlace.getId());
        }
        return placeIndexInfos;
    }

    /*public List<PlaceSalePlanInfo> getPlaceSalePlanSerach(
            @NotNull(message = "场馆对象不能为空") TbBizPlace tbBizPlace,
            List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans) {
        List<PlaceSalePlanInfo> reqPlaceSalePlans = new ArrayList<>();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sf1 = new SimpleDateFormat("HH:mm:ss");
        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlans) {
            PlaceSalePlanInfo reqPlaceSalePlan =
                    new PlaceSalePlanInfo();
            reqPlaceSalePlan.setSalePlanId(tbBizPlace.getId());
            reqPlaceSalePlan.setPlaceId(tbBizPlace.getId());
            reqPlaceSalePlan.setDate(sf.format(tbBizPlaceUnitSalePlan.getDate()));
            reqPlaceSalePlan.setStartTime(sf1.format(tbBizPlaceUnitSalePlan.getStartTime()));
            reqPlaceSalePlan.setEndTime(sf1.format(tbBizPlaceUnitSalePlan.getEndTime()));
            reqPlaceSalePlan.setIsSaled(Integer.parseInt(tbBizPlaceUnitSalePlan.getStatus() + ""));
            reqPlaceSalePlans.add(reqPlaceSalePlan);
        }
        return reqPlaceSalePlans;
    }*/

    @Override
    public com.quanyan.search.entity.request.ReqPlaceSalePlan tbPlaceSalePlan2ReqPlaceSalePlan(TbBizPlaceUnitSalePlan
                                                                                                       tbBizPlaceUnitSalePlan) {
        com.quanyan.search.entity.request.ReqPlaceSalePlan reqPlaceSalePlan =
                new com.quanyan.search.entity.request.ReqPlaceSalePlan();
        BeanUtils.copyProperties(tbBizPlaceUnitSalePlan, reqPlaceSalePlan);
        if (tbBizPlaceUnitSalePlan.getStatus().intValue() == PlaceConstants.PLACE_PREORDER_STATUS.intValue()) {
            reqPlaceSalePlan.setIsSaled(PlaceConstants.IS_SALE);
        } else {
            reqPlaceSalePlan.setIsSaled(PlaceConstants.IS_NOT_SALE);
        }
        return reqPlaceSalePlan;
    }

    public List<com.quanyan.search.entity.request.ReqPlaceSalePlan> getReqPlaceSalePlanSerach(
            @NotNull(message = "场馆对象不能为空") TbBizPlace tbBizPlace,
            List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans) {
        List<com.quanyan.search.entity.request.ReqPlaceSalePlan> reqPlaceSalePlans = new ArrayList<>();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sf1 = new SimpleDateFormat("HH:mm:ss");
        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlans) {
            com.quanyan.search.entity.request.ReqPlaceSalePlan reqPlaceSalePlan =
                    new com.quanyan.search.entity.request.ReqPlaceSalePlan();
            reqPlaceSalePlan.setId(tbBizPlaceUnitSalePlan.getId());
            reqPlaceSalePlan.setPlaceId(tbBizPlace.getId());
            reqPlaceSalePlan.setDate(sf.format(tbBizPlaceUnitSalePlan.getDate()));
            reqPlaceSalePlan.setStartTime(sf1.format(tbBizPlaceUnitSalePlan.getStartTime()));
            reqPlaceSalePlan.setEndTime(sf1.format(tbBizPlaceUnitSalePlan.getEndTime()));
            reqPlaceSalePlan.setIsSaled(Integer.parseInt(tbBizPlaceUnitSalePlan.getStatus() + ""));
            reqPlaceSalePlans.add(reqPlaceSalePlan);
        }
        return reqPlaceSalePlans;
    }

    @Override
    public List<TbBizPlaceUnitSalePlan> getSalePlanUnitId(List<String> saleids) {
        if (CollectionUtils.isEmpty(saleids)) {
            return null;
        }
        TbBizPlaceUnitSalePlanExample tbBizPlaceUnitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
        tbBizPlaceUnitSalePlanExample.createCriteria().andSaleIdIn(saleids);
        List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlans = this
                .tbBizPlaceUnitSalePlanMapper.selectByExample(tbBizPlaceUnitSalePlanExample);
        if (CollectionUtils.isEmpty(tbBizPlaceUnitSalePlans)) {
            return null;
        }

        return tbBizPlaceUnitSalePlans;
    }

    @Override
    public List<TbBizPlaceUnitSalePlan> getTbBizPlaceUnitSalePlansByPlaeId(
            @NotNull(message = "场馆ID不能为空") Integer placeId, Integer days) {
        TbBizPlaceUnitSalePlanExample tbBizPlaceUnitSalePlanExample = new TbBizPlaceUnitSalePlanExample();
        TbBizPlaceUnitSalePlanExample.Criteria criteria = tbBizPlaceUnitSalePlanExample.createCriteria();
        criteria.andPlaceIdEqualTo(placeId).andUnitTypeEqualTo(PlaceConstants.UNIT_TYPE_BASE);
        if (!StringUtils.isEmpty(days)){
            criteria.andDateBetween(new Date(), DateTime.now().plusDays(days).toDate());
        }
        return this.tbBizPlaceUnitSalePlanMapper.selectByExample(tbBizPlaceUnitSalePlanExample);
    }

    @Override
    public List<TbBizPlaceCategory> getTbBizPlaceCategoryByPlaceId(@NotNull(message = "场馆ID不能为空") Integer placeId) {
        TbBizPlaceCategoryExample tbBizPlaceCategoryExample = new TbBizPlaceCategoryExample();
        tbBizPlaceCategoryExample.createCriteria().andPlaceIdEqualTo(placeId);
        return this.tbBizPlaceCategoryMapper.selectByExample(tbBizPlaceCategoryExample);
    }

    @Override
    public Map<Integer, String> getSysCategoryMap() {
        List<RespCategory> respCategories = null;
        RedisKey rediskey = new RedisKey(RedisConstants.PLACE_FAMILY_KEY,
                PlaceConstants.PLACE_ALL_CATEGORIES_REDIS_KEY);
        //缓存取
        respCategories = (List<RespCategory>) redisTemplate.get(rediskey);
        if (CollectionUtils.isEmpty(respCategories)) {
            //缓存没有就查db
            respCategories = this.getSysCategroyInfo();
            if (CollectionUtils.isEmpty(respCategories)) {
                return null;
            }
        }
        Map<Integer, String> map = new HashMap<>(respCategories.size());
        for (RespCategory respCategory : respCategories) {
            map.put(respCategory.getId(), respCategory.getName());
        }
        return map;
    }

    @Override
    public RespCategory getRespCategoryByName(String categoryName) {
        Map<Integer, String> map = this.getSysCategoryMap();
        if (StringUtils.isEmpty(map)) {
            return null;
        }
        Iterator<Map.Entry<Integer,String>> iteratior = map.entrySet().iterator();
        while(iteratior.hasNext()){
            Map.Entry entry = iteratior.next();
            Integer key = (Integer)entry.getKey();
            if (categoryName.equals(map.get(key))){
                RespCategory respCategory = new RespCategory();
                respCategory.setId(key);
                respCategory.setName(categoryName);
                return respCategory;
            }
        }
       /* for (Integer id : map.keySet()) {
            if (map.get(id).equals(categoryName)) {
                RespCategory respCategory = new RespCategory();
                respCategory.setId(id);
                respCategory.setName(categoryName);
                return respCategory;
            }
        }*/
        return null;
    }


    /**
     * 转换TbBizPlaceOrder到RespBizPlaceOrderInfo
     *
     * @param tbBizPlaceOrders
     * @return
     */
    private List<RespUserBizPlaceOrderInfo> tbBizPlaceOrders2RespBizPlaceOrderInfos(
            List<TbBizPlaceOrder> tbBizPlaceOrders, Integer opType,Integer orderStatus, Integer isEnable) {
        List<RespUserBizPlaceOrderInfo> respUserBizPlaceOrderInfos = new ArrayList<>();
        for (TbBizPlaceOrder tbBizPlaceOrder : tbBizPlaceOrders) {
            RespUserBizPlaceOrderInfo respUserBizPlaceOrderInfo = this.tbPlaceOrderInfo2Resp(tbBizPlaceOrder, opType, orderStatus, isEnable);
            if (!StringUtils.isEmpty(respUserBizPlaceOrderInfo)){
                respUserBizPlaceOrderInfos.add(respUserBizPlaceOrderInfo);
            }
        }
        return respUserBizPlaceOrderInfos;
    }

    private RespUserBizPlaceOrderInfo tbPlaceOrderInfo2Resp(TbBizPlaceOrder tbBizPlaceOrder, Integer opType,
                                                            Integer orderStatus, Integer isEnable) {
//        Map<String,Object> queryMap = new HashMap<>();
//        queryMap.put("orderNo", tbBizPlaceOrder.getPlaceOrderId());
//        queryMap.put("uid", tbBizPlaceOrder.getUid());


//        List<PlaceOrderSalePlan> placeOrderSalePlanList = tbBizPlaceOrderManagerMapper.selectOrderStatus(queryMap);

        /*String startTime = placeOrderSalePlanList.get(0).getStartTime();
        String startDate = placeOrderSalePlanList.get(0).getDate();
        Date date = DateUtils.dateStrToDate(startDate + " " + startTime);*/

        /*if (isEnable.intValue() == Constants.IS_YES){
            if (new Date().getTime() > date.getTime()){
                return null;
            }
        }*/
        RespBizPlaceBaseInfo respBizPlaceBaseInfo = placeBaseInfoUtils(tbBizPlaceOrder.getPlaceId());
        RespUserBizPlaceOrderInfo respUserBizPlaceOrderInfo = new RespUserBizPlaceOrderInfo();
        BeanUtils.copyProperties(respBizPlaceBaseInfo, respUserBizPlaceOrderInfo);
        respUserBizPlaceOrderInfo.setOrderTime(tbBizPlaceOrder.getOrderTime().getTime());
        respUserBizPlaceOrderInfo.setCategoryId(tbBizPlaceOrder.getCategoryId());
        respUserBizPlaceOrderInfo.setOrderId(tbBizPlaceOrder.getPlaceOrderId());
        respUserBizPlaceOrderInfo.setPayStatus(tbBizPlaceOrder.getPayStatus());
        respUserBizPlaceOrderInfo.setOrderStatus(tbBizPlaceOrder.getOrderStatus());
        respUserBizPlaceOrderInfo.setUid(tbBizPlaceOrder.getUid());
        respUserBizPlaceOrderInfo.setPlaceId(tbBizPlaceOrder.getPlaceId());
        respUserBizPlaceOrderInfo.setSourceType(tbBizPlaceOrder.getSourceType());
        respUserBizPlaceOrderInfo.setUseType(tbBizPlaceOrder.getUseType());
        respUserBizPlaceOrderInfo.setPrice(tbBizPlaceOrder.getDebit());
        //// TODO: 16/6/21 查询openid
        /*APIResponse<RespUserInfoBase> response = this.userServiceFacade.queryUserInfo(tbBizPlaceOrder.getUid());
        if (response.isRet()){
            respUserBizPlaceOrderInfo.setOpenid(response.getData().get);
        }*/
        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(tbBizPlaceOrder.getPlaceId());
        respUserBizPlaceOrderInfo.setCommentCount(tbBizPlace.getCommentCount());
        respUserBizPlaceOrderInfo.setPlaceScore(tbBizPlace.getPlaceScore());

        List<Integer> values = new ArrayList<>();
        values.add(PlaceConstants.PAY_WAY_ALIPAY);
        values.add(PlaceConstants.PAY_WAY_WEICHAT);
        values.add(PlaceConstants.PAY_WAY_WEICHATH5);
        values.add(PlaceConstants.PAY_WAY_UNION_PAY);
        values.add(PlaceConstants.PAY_WAY_APPLE_PAY);
        values.add(PlaceConstants.PAY_WAY_FOR_CARD);
        values.add(PlaceConstants.PAY_WAY_FOR_WEB_ALIPAY);

        TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
        TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
        tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(tbBizPlaceOrder.getPlaceOrderId()).andPayTypeIn(values);
        List<TbBizPlacePayItem> tbBizPlacePayItemList = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);

        /*if (CollectionUtils.isNotEmpty(tbBizPlacePayItemList)) {
            respUserBizPlaceOrderInfo.setLowestPrice(tbBizPlacePayItemList.get(0).getAmount());
        }*/
        Map<Integer, String> map = getSysCategoryMap();
        if (map.isEmpty()) {
            return null;
        }


        // 获取场馆退订小时数
        /*TbBizPlaceRuleExample tbBizPlaceRuleExample = new TbBizPlaceRuleExample();
        tbBizPlaceRuleExample.createCriteria().andPlaceIdEqualTo(tbBizPlaceOrder.getPlaceId());
        List<TbBizPlaceRule> tbBizPlaceRules = this.tbBizPlaceRuleMapper.selectByExample(tbBizPlaceRuleExample);
*/
        RespCategory respCategory = new RespCategory();
        respCategory.setId(tbBizPlaceOrder.getCategoryId());
        respCategory.setName(map.get(tbBizPlaceOrder.getCategoryId()));
        respUserBizPlaceOrderInfo.setRespCategory(respCategory);

        if (StringUtils.isEmpty(opType) && tbBizPlaceOrder.getOrderStatus().intValue() == PlaceConstants
                .ORDER_COMPLETE_PAY_STATUS.intValue()) {
            if (hasComment(tbBizPlaceOrder.getUid(), tbBizPlaceOrder.getPlaceId(), tbBizPlaceOrder.getPlaceOrderId())) {
                respUserBizPlaceOrderInfo.setCommented(Constants.IS_YES);
            } else {
                respUserBizPlaceOrderInfo.setCommented(Constants.IS_NO);
            }

        } else if (tbBizPlaceOrder.getOrderStatus().intValue() == PlaceConstants.ORDER_PREPAY_STATUS.intValue()){
            if (CollectionUtils.isNotEmpty(tbBizPlacePayItemList)){
                respUserBizPlaceOrderInfo.setPrice(tbBizPlacePayItemList.get(0).getAmount());
            }
        }
        /*if (CollectionUtils.isNotEmpty(placeOrderSalePlanList)){
            Integer time = 0;
            if(CollectionUtils.isEmpty(tbBizPlaceRules)){
                time = PlaceConstants.PLACE_UNSUBSCRIBE_TIME;
            }
            else {
                time = tbBizPlaceRules.get(0).getUnsubscribeTime();
            }

            if(time > 0){
                respUserBizPlaceOrderInfo.setStartDate(date.getTime() - time*60*60*1000);
            }
            else if(time == 0){
                respUserBizPlaceOrderInfo.setStartDate(PlaceConstants.NOT_UNSUBSCRIBE_TIMESTAMP);
            }
        }
        if (CollectionUtils.isNotEmpty(tbBizPlaceRules)){
            respUserBizPlaceOrderInfo.setUnsubscribeTime(tbBizPlaceRules.get(0).getUnsubscribeTime());
        }*/
        return respUserBizPlaceOrderInfo;
    }

    public boolean hasComment(Integer uid, Integer placeId, String orderid) {
        //// TODO: 16/6/24 调用评价列表
        ReqIsComment reqIsComment = new ReqIsComment();
        reqIsComment.setSystemCode(Constants.PLACE_SYSTEM_CODE);
        reqIsComment.setBusinessCode(Constants.PLACE_BOOKING_CODE);
        reqIsComment.setBusinessId(placeId);
        reqIsComment.setOrderNo(orderid);
        return commentServiceFacade.checkIsCommentPlace(reqIsComment);

    }

    public RespBizPlaceBaseInfo placeBaseInfoUtils(Integer placeId) {
        RespBizPlaceBaseInfo respBizPlaceBaseInfo = new RespBizPlaceBaseInfo();
        //获取场馆基本信息
        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(placeId);
        respBizPlaceBaseInfo.setPlaceScore(tbBizPlace.getPlaceScore());
        respBizPlaceBaseInfo.setCommentCount(tbBizPlace.getCommentCount());
        //获取场馆图片信息
        TbPlaceImageExample tbPlaceImageExample = new TbPlaceImageExample();
        TbPlaceImageExample.Criteria tbPlaceImageCriteria = tbPlaceImageExample.createCriteria();
        tbPlaceImageCriteria.andTopicIdEqualTo(placeId);
        List<TbPlaceImage> tbPlaceImageList = tbPlaceImageMapper.selectUrlByExample(tbPlaceImageExample);

        //获取场馆运动类别信息
        TbBizPlaceCategoryExample tbBizPlaceCategoryExample = new TbBizPlaceCategoryExample();
        TbBizPlaceCategoryExample.Criteria tbBizPlaceCategoryCriteria = tbBizPlaceCategoryExample.createCriteria();
        tbBizPlaceCategoryCriteria.andPlaceIdEqualTo(placeId);
        List<TbBizPlaceCategory> tbBizPlaceCategoryList =
                tbBizPlaceCategoryMapper.selectByExample(tbBizPlaceCategoryExample);
        List<RespCategory> categorys = new ArrayList<>();
        if (tbBizPlaceCategoryList != null && tbBizPlaceCategoryList.size() > 0) {
            for (TbBizPlaceCategory tbBizPlaceCategory : tbBizPlaceCategoryList) {
                RespCategory respCategory = new RespCategory();
                respCategory.setId(tbBizPlaceCategory.getCategoryId());
                respCategory.setName(getCommonDataCache("cagetory" + tbBizPlaceCategory.getCategoryId().toString()));
                categorys.add(respCategory);
            }
            respBizPlaceBaseInfo.setCategorys(categorys);

        }


        if (!StringUtils.isEmpty(tbBizPlace)){
            //获取场馆城市信息
            TbCity tbCity = tbCityMapper.selectByPrimaryKey(tbBizPlace.getCityId());
            //获取场馆区域信息
            TbDistrict tbDistrict = tbDistrictMapper.selectByPrimaryKey(tbBizPlace.getDistrictId());

            try {
                BeanUtils.copyProperties(tbBizPlace, respBizPlaceBaseInfo);
                List<RespImage> respImageList = new ArrayList<>();
                for (TbPlaceImage tbPlaceImage : tbPlaceImageList) {
                    RespImage respImage = new RespImage();
                    BeanUtils.copyProperties(tbPlaceImage, respImage);
                    respImageList.add(respImage);
                }
                respBizPlaceBaseInfo.setImages(respImageList);

                RespCity respCity = new RespCity();
                BeanUtils.copyProperties(tbCity, respCity);
                respBizPlaceBaseInfo.setCityObj(respCity);

                RespDistrict respDistrict = new RespDistrict();
                BeanUtils.copyProperties(tbDistrict, respDistrict);
                respBizPlaceBaseInfo.setDistrictObj(respDistrict);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return respBizPlaceBaseInfo;
    }

    public APIResponse getPlaceCommonData() {
        PlaceCommonDataVo placeCommonDataVo = new PlaceCommonDataVo();
        Class<PlaceCommonDataVo> cls = PlaceCommonDataVo.class;
        Map<String,String> condition = new HashMap<String,String>();

        condition.put("网球场地类型","tennis_unit_type");
        condition.put("羽毛球场地类型","badminton_unit_type");
        condition.put("篮球场地类型","basketball_unit_type");
        condition.put("足球场地类型","football_unit_type");

        condition.put("网球场地材质","tennis_unit_texture");
        condition.put("羽毛球场地材质","badminton_unit_texture");
        condition.put("篮球场地材质","basketball_unit_texture");
        condition.put("足球场地材质","football_unit_texture");

        condition.put("灯光类型","light_type");
        condition.put("时间类型","time_type");
        condition.put("场馆属性","manage_type");
        condition.put("足球场地规模","football_field_scale");

        try {
            Set<Map.Entry<String,String>> set = condition.entrySet();
            for (Map.Entry<String,String> map : set){
                DictExample dictExample = new DictExample();
                DictExample.Criteria dictCriteria = dictExample.createCriteria();
                dictCriteria.andTagEqualTo(map.getKey());
                Field field = cls.getDeclaredField(map.getValue());
                field.setAccessible(true);
                List<Dict> result = this.dictMapper.selectDataValueByExample(dictExample);
                field.set(placeCommonDataVo,result);
            }
        }
        catch (Exception e){
            e.printStackTrace();
            APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR);
        }

        CagetoryExample cagetoryExample = new CagetoryExample();
        CagetoryExample.Criteria cagetoryCriteria = cagetoryExample.createCriteria();
        cagetoryCriteria.andIdLessThanOrEqualTo(4);
        List<Cagetory> cagetoryList = this.cagetoryMapper.selectNameByExample(cagetoryExample);
        placeCommonDataVo.setCagetory_list(cagetoryList);

        return APIResponse.returnSuccess(placeCommonDataVo);
    }

    @Override
    public String getCommonDataCache(String key){
        if(placeCommonDataMap.size() == 0){//初始化时加载数据库配置表中数据到placeCommonDataMap中
            APIResponse<PlaceCommonDataVo> apiResponse = getPlaceCommonData();
            PlaceCommonDataVo placeCommonDataVo = apiResponse.getData();
            List<Dict> placeCommonDataList = new ArrayList<Dict>();

            placeCommonDataList.addAll(placeCommonDataVo.getBadminton_unit_texture());
            placeCommonDataList.addAll(placeCommonDataVo.getBadminton_unit_type());
            placeCommonDataList.addAll(placeCommonDataVo.getBasketball_unit_texture());
            placeCommonDataList.addAll(placeCommonDataVo.getBasketball_unit_type());
            placeCommonDataList.addAll(placeCommonDataVo.getFootball_field_scale());
            placeCommonDataList.addAll(placeCommonDataVo.getFootball_unit_texture());
            placeCommonDataList.addAll(placeCommonDataVo.getFootball_unit_type());
            placeCommonDataList.addAll(placeCommonDataVo.getTennis_unit_texture());
            placeCommonDataList.addAll(placeCommonDataVo.getTennis_unit_type());
            placeCommonDataList.addAll(placeCommonDataVo.getTime_type());
            placeCommonDataList.addAll(placeCommonDataVo.getManage_type());
            placeCommonDataList.addAll(placeCommonDataVo.getLight_type());

            List<Cagetory> cagetoryList = placeCommonDataVo.getCagetory_list();
            List<Dict> dictList = new ArrayList<>();
            for (Cagetory cagetory : cagetoryList) {
                Dict dict = new Dict();
                dict.setDataKey("cagetory"+cagetory.getId().toString());
                dict.setDataValue(cagetory.getName());
                dictList.add(dict);
            }
            placeCommonDataList.addAll(dictList);

            for(Dict dict : placeCommonDataList){
                placeCommonDataMap.put(dict.getDataKey(), dict.getDataValue());
            }
        }
        return placeCommonDataMap.get(key);
    }

    /*
     *  更新订单中销售计划[可能是组合场地的销售计划]的状态
     */
    public int updateSalePlanByPrimaryKeyList(ReqPlaceOrderListVo reqPlaceOrderListVo) {
        int subSucc = 0;
        int idSize = 0;
        int saleIdSize = 0;

        List<UnitSalePlan> unitSalePlanList = reqPlaceOrderListVo.getUnitSalePlanIdList();
        if (unitSalePlanList != null) {
            saleIdSize =  unitSalePlanList.size();
        }
        List<Integer> salePlanIdList = reqPlaceOrderListVo.getSalePlanPrimaryKeyList();
        if (salePlanIdList != null) {
            idSize = salePlanIdList.size();
        }

        if (saleIdSize == 0 && idSize == 0){
            return -1;
        }

        if (saleIdSize > 0 && idSize > 0 && saleIdSize != idSize) {
            return -1;
        }

        // 先查询每个销售计划的类型 (使用已有接口)
        ReqPlaceOrderListVo reqTemp = new ReqPlaceOrderListVo();
        reqTemp.setUnitSalePlanIdList(reqPlaceOrderListVo.getUnitSalePlanIdList());
        reqTemp.setSalePlanPrimaryKeyList(reqPlaceOrderListVo.getSalePlanPrimaryKeyList());
        List<TbBizPlaceUnitSalePlan> salePlans = placeUnitSalePlanMapper.selectSalePlanForUpdate(reqTemp);
        if (salePlans != null && salePlans.size() > 0) {
            for (TbBizPlaceUnitSalePlan salePlan : salePlans) {
                // 如果是组合场地的订单,要同时更新子场地销售计划
                if (PlaceConstants.UNIT_TYPE_COMBINE.equals(salePlan.getUnitType())) {
                    String subSaleplans = salePlan.getSubSaleplans();
                    if (subSaleplans == null || subSaleplans.isEmpty()) {
                        continue;
                    }

                    List<String> subSalePlanIds = Arrays.asList(subSaleplans.split("[|]"));
                    List<UnitSalePlan> subSalePlanList = new ArrayList<>();

                    if (subSalePlanIds != null && subSalePlanIds.size() > 0) {
                        for (String salePlanId : subSalePlanIds) {
                            UnitSalePlan subUSP = new UnitSalePlan();
                            subUSP.setSaleId(salePlanId);
                            subSalePlanList.add(subUSP);
                        }
                    }

                    if (subSalePlanList.size() > 0) {
                        ReqPlaceOrderListVo subReq = new ReqPlaceOrderListVo();
                        BeanCopierUtils.copyProperties(reqPlaceOrderListVo, subReq);

                        subReq.setUnitSalePlanIdList(subSalePlanList);
                        subReq.setSalePlanPrimaryKeyList(null);
                        if (CollectionUtils.isNotEmpty(subSalePlanList)){
                            int ret = placeUnitSalePlanMapper.updateByPrimaryKeyList(subReq);
                            if (ret >= subSalePlanList.size()) {
                                subSucc++;
                            }
                        }
                    }
                } else {
                    subSucc++;
                }
            }
        }

        if (subSucc < idSize || subSucc < saleIdSize) {
            return -1;
        }

        return placeUnitSalePlanMapper.updateByPrimaryKeyList(reqPlaceOrderListVo);
    }

    /**
     * 检验销售计划有没有重叠
     * @param tbBizPlaceUnitSalePlanList
     * @return
     */
    public APIResponse salePlansVerification(List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList) {
        Set<String> uniqSaleIds = new HashSet<>();

        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
            List<String> saleIds = new ArrayList<>();

            if (tbBizPlaceUnitSalePlan == null) {
                continue;
            }

            String saleId = tbBizPlaceUnitSalePlan.getSaleId();
            if (saleId != null) {
                saleIds.add(saleId);
            }

            if (UNIT_TYPE_COMBINE.equals(tbBizPlaceUnitSalePlan.getUnitType())) {
                String subSaleplans = tbBizPlaceUnitSalePlan.getSubSaleplans();
                List<String> subSaleplanIds = new ArrayList<>();
                if (subSaleplans != null) {
                    subSaleplanIds = Arrays.asList(subSaleplans.split("[|]"));
                }

                if (subSaleplanIds != null && subSaleplanIds.size() > 0) {
                    saleIds.addAll(subSaleplanIds);
                }
            }

            for (String curSaleId : saleIds) {
                if (uniqSaleIds.contains(curSaleId)) {
                    return APIResponse.returnFail("销售计划" + saleId + "有重叠！" );
                } else {
                    uniqSaleIds.add(curSaleId);
                }
            }
        }

        return null;
    }

	@Override
	public List<TbBizPlacePayItem> convertOrderPayItem(List<TbBizPlaceOrderItem> tbBizPlaceOrderItems,Integer payType
			,TbBizPlaceMemberCard tbBizPlaceMemberCard) {
		List<TbBizPlacePayItem> result = new ArrayList<TbBizPlacePayItem>();
		if (CollectionUtils.isNotEmpty(tbBizPlaceOrderItems)) {
			
			for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems) {
				TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
				tbBizPlacePayItem.setPlaceOrderId(tbBizPlaceOrderItem.getPlaceOrderId());
				tbBizPlacePayItem.setOrderItemUuid(UUIDUtils.getUUID());
				
				if (tbBizPlaceMemberCard != null && tbBizPlaceMemberCard.getIsOldMember() == Constants.BYTE_ONE){
					tbBizPlacePayItem.setPayType(Integer.parseInt(PlaceConstants.PLACE_ADMIN_PAY_WAYS_BOSS));
					tbBizPlacePayItem.setAdminPayType(Integer.parseInt(PlaceConstants.PLACE_ADMIN_PAY_WAYS_BOSS));
				} else {
					tbBizPlacePayItem.setPayType(payType);
					tbBizPlacePayItem.setAdminPayType(PayTypeEnum.getEnum(payType).getUnifiedId());
				}
				tbBizPlacePayItem.setAmount(tbBizPlaceOrderItem.getSalePrice());
				tbBizPlacePayItem.setAmountType(PlaceConstants.DEBIT_TYPE);
				tbBizPlacePayItem.setCreateTime(new Date());
				tbBizPlacePayItem.setUpdateTime(new Date());
				result.add(tbBizPlacePayItem);
			}
		}
		return result;
	}

	@Override
	public List<TbBizPlaceOrderDiscountItem> convertOrderDiscountItem(List<TbBizPlaceOrderItem> tbBizPlaceOrderItems,
			TbBizPlaceMemberCard tbBizPlaceMemberCard) {
		List<TbBizPlaceOrderDiscountItem>  result = new ArrayList<TbBizPlaceOrderDiscountItem>();
		Predicate predicate = new Predicate() {
			@Override
			public boolean evaluate(Object object) {
				if (object instanceof TbBizPlaceOrderItem) {
					TbBizPlaceOrderItem TbBizPlaceOrderItem = (TbBizPlaceOrderItem)object;
					return TbBizPlaceOrderItem.getAdjustPrice() != null 
							&& TbBizPlaceOrderItem.getAdjustPrice().compareTo(new BigDecimal(0)) > 0;
				}
				return false;
			}
		};
		if (tbBizPlaceMemberCard != null ||	org.apache.commons.collections.CollectionUtils.exists(tbBizPlaceOrderItems, predicate)) {
			if (CollectionUtils.isNotEmpty(tbBizPlaceOrderItems)) {
				for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems) {
					TbBizPlaceOrderDiscountItem discountItem = new TbBizPlaceOrderDiscountItem();
					discountItem.setOrderItemUuid(tbBizPlaceOrderItem.getItemUuid());
					discountItem.setPlaceOrderId(tbBizPlaceOrderItem.getPlaceOrderId());
					discountItem.setStatus(PlaceConstants.ORDER_PAYED_STATUS.intValue());
					//会员优惠
					if (tbBizPlaceMemberCard != null) {
					      discountItem.setDiscountMember(tbBizPlaceOrderItem.getOriginPrice().subtract(tbBizPlaceOrderItem.getMemberPrice()));
						//折扣卡，储值折扣卡
					  if(PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType()) || PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){//折扣卡 ,储值折扣打折
						  discountItem.setDiscountDiscountMember(tbBizPlaceOrderItem.getMemberPrice().subtract(tbBizPlaceOrderItem.getSalePrice()));
		              }
					      discountItem.setMemberCardNo(tbBizPlaceMemberCard.getInnerCardNo());
					}
					//手动调价
					if (tbBizPlaceOrderItem.getAdjustPrice() != null) {
						  discountItem.setDiscountAdjust(tbBizPlaceOrderItem.getAdjustPrice());
					}
					discountItem.setCreateTime(new Date());
					discountItem.setUpdateTime(new Date());
					result.add(discountItem);
				}
			}
		}
		return result;
	}
}
